blob: 186ec3b39f0831c71f00e963e9c05b93ba46085f [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 Armbruster2114f5a2015-04-02 13:12:21 +020016import getopt
Lluís Vilanova33aaad52014-05-02 15:52:35 +020017import os
Markus Armbruster2caba362013-07-27 17:41:56 +020018import sys
Markus Armbruster47299262015-05-14 06:50:47 -060019import string
Michael Roth0f923be2011-07-19 14:50:39 -050020
Eric Blakeb52c4b92015-05-04 09:05:00 -060021builtin_types = {
Kevin Wolf69dd62d2013-07-08 16:14:21 +020022 'str': 'QTYPE_QSTRING',
23 'int': 'QTYPE_QINT',
24 'number': 'QTYPE_QFLOAT',
25 'bool': 'QTYPE_QBOOL',
26 'int8': 'QTYPE_QINT',
27 'int16': 'QTYPE_QINT',
28 'int32': 'QTYPE_QINT',
29 'int64': 'QTYPE_QINT',
30 'uint8': 'QTYPE_QINT',
31 'uint16': 'QTYPE_QINT',
32 'uint32': 'QTYPE_QINT',
33 'uint64': 'QTYPE_QINT',
Eric Blakecb17f792015-05-04 09:05:01 -060034 'size': 'QTYPE_QINT',
Kevin Wolf69dd62d2013-07-08 16:14:21 +020035}
36
Eric Blake10d4d992015-05-04 09:05:23 -060037# Whitelist of commands allowed to return a non-dictionary
38returns_whitelist = [
39 # From QMP:
40 'human-monitor-command',
41 'query-migrate-cache-size',
42 'query-tpm-models',
43 'query-tpm-types',
44 'ringbuf-read',
45
46 # From QGA:
47 'guest-file-open',
48 'guest-fsfreeze-freeze',
49 'guest-fsfreeze-freeze-list',
50 'guest-fsfreeze-status',
51 'guest-fsfreeze-thaw',
52 'guest-get-time',
53 'guest-set-vcpus',
54 'guest-sync',
55 'guest-sync-delimited',
56
57 # From qapi-schema-test:
58 'user_def_cmd3',
59]
60
Eric Blake4dc2e692015-05-04 09:05:17 -060061enum_types = []
62struct_types = []
63union_types = []
64events = []
65all_names = {}
66
Lluís Vilanovaa719a272014-05-07 20:46:15 +020067def error_path(parent):
68 res = ""
69 while parent:
70 res = ("In file included from %s:%d:\n" % (parent['file'],
71 parent['line'])) + res
72 parent = parent['parent']
73 return res
74
Markus Armbruster2caba362013-07-27 17:41:56 +020075class QAPISchemaError(Exception):
76 def __init__(self, schema, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020077 self.input_file = schema.input_file
Markus Armbruster2caba362013-07-27 17:41:56 +020078 self.msg = msg
Wenchao Xia515b9432014-03-04 18:44:33 -080079 self.col = 1
80 self.line = schema.line
81 for ch in schema.src[schema.line_pos:schema.pos]:
82 if ch == '\t':
Markus Armbruster2caba362013-07-27 17:41:56 +020083 self.col = (self.col + 7) % 8 + 1
84 else:
85 self.col += 1
Lluís Vilanovaa719a272014-05-07 20:46:15 +020086 self.info = schema.parent_info
Markus Armbruster2caba362013-07-27 17:41:56 +020087
88 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020089 return error_path(self.info) + \
90 "%s:%d:%d: %s" % (self.input_file, self.line, self.col, self.msg)
Markus Armbruster2caba362013-07-27 17:41:56 +020091
Wenchao Xiab86b05e2014-03-04 18:44:34 -080092class QAPIExprError(Exception):
93 def __init__(self, expr_info, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020094 self.info = expr_info
Wenchao Xiab86b05e2014-03-04 18:44:34 -080095 self.msg = msg
96
97 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020098 return error_path(self.info['parent']) + \
99 "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800100
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200101class QAPISchema:
Michael Roth0f923be2011-07-19 14:50:39 -0500102
Benoît Canet24fd8482014-05-16 12:51:56 +0200103 def __init__(self, fp, input_relname=None, include_hist=[],
104 previously_included=[], parent_info=None):
105 """ include_hist is a stack used to detect inclusion cycles
106 previously_included is a global state used to avoid multiple
107 inclusions of the same file"""
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200108 input_fname = os.path.abspath(fp.name)
109 if input_relname is None:
110 input_relname = fp.name
111 self.input_dir = os.path.dirname(input_fname)
112 self.input_file = input_relname
113 self.include_hist = include_hist + [(input_relname, input_fname)]
Benoît Canet24fd8482014-05-16 12:51:56 +0200114 previously_included.append(input_fname)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200115 self.parent_info = parent_info
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200116 self.src = fp.read()
117 if self.src == '' or self.src[-1] != '\n':
118 self.src += '\n'
119 self.cursor = 0
Wenchao Xia515b9432014-03-04 18:44:33 -0800120 self.line = 1
121 self.line_pos = 0
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200122 self.exprs = []
123 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500124
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200125 while self.tok != None:
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200126 expr_info = {'file': input_relname, 'line': self.line, 'parent': self.parent_info}
127 expr = self.get_expr(False)
128 if isinstance(expr, dict) and "include" in expr:
129 if len(expr) != 1:
130 raise QAPIExprError(expr_info, "Invalid 'include' directive")
131 include = expr["include"]
132 if not isinstance(include, str):
133 raise QAPIExprError(expr_info,
134 'Expected a file name (string), got: %s'
135 % include)
136 include_path = os.path.join(self.input_dir, include)
Stefan Hajnoczi7ac9a9d2014-08-27 12:08:51 +0100137 for elem in self.include_hist:
138 if include_path == elem[1]:
139 raise QAPIExprError(expr_info, "Inclusion loop for %s"
140 % include)
Benoît Canet24fd8482014-05-16 12:51:56 +0200141 # skip multiple include of the same file
142 if include_path in previously_included:
143 continue
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200144 try:
145 fobj = open(include_path, 'r')
Luiz Capitulino34788812014-05-20 13:50:19 -0400146 except IOError, e:
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200147 raise QAPIExprError(expr_info,
148 '%s: %s' % (e.strerror, include))
Benoît Canet24fd8482014-05-16 12:51:56 +0200149 exprs_include = QAPISchema(fobj, include, self.include_hist,
150 previously_included, expr_info)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200151 self.exprs.extend(exprs_include.exprs)
152 else:
153 expr_elem = {'expr': expr,
154 'info': expr_info}
155 self.exprs.append(expr_elem)
Michael Roth0f923be2011-07-19 14:50:39 -0500156
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200157 def accept(self):
158 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200159 self.tok = self.src[self.cursor]
Markus Armbruster2caba362013-07-27 17:41:56 +0200160 self.pos = self.cursor
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200161 self.cursor += 1
162 self.val = None
Michael Roth0f923be2011-07-19 14:50:39 -0500163
Markus Armbrusterf1a145e2013-07-27 17:42:01 +0200164 if self.tok == '#':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200165 self.cursor = self.src.find('\n', self.cursor)
166 elif self.tok in ['{', '}', ':', ',', '[', ']']:
167 return
168 elif self.tok == "'":
169 string = ''
170 esc = False
171 while True:
172 ch = self.src[self.cursor]
173 self.cursor += 1
174 if ch == '\n':
Markus Armbruster2caba362013-07-27 17:41:56 +0200175 raise QAPISchemaError(self,
176 'Missing terminating "\'"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200177 if esc:
Eric Blakea7f59662015-05-04 09:05:36 -0600178 if ch == 'b':
179 string += '\b'
180 elif ch == 'f':
181 string += '\f'
182 elif ch == 'n':
183 string += '\n'
184 elif ch == 'r':
185 string += '\r'
186 elif ch == 't':
187 string += '\t'
188 elif ch == 'u':
189 value = 0
190 for x in range(0, 4):
191 ch = self.src[self.cursor]
192 self.cursor += 1
193 if ch not in "0123456789abcdefABCDEF":
194 raise QAPISchemaError(self,
195 '\\u escape needs 4 '
196 'hex digits')
197 value = (value << 4) + int(ch, 16)
198 # If Python 2 and 3 didn't disagree so much on
199 # how to handle Unicode, then we could allow
200 # Unicode string defaults. But most of QAPI is
201 # ASCII-only, so we aren't losing much for now.
202 if not value or value > 0x7f:
203 raise QAPISchemaError(self,
204 'For now, \\u escape '
205 'only supports non-zero '
206 'values up to \\u007f')
207 string += chr(value)
208 elif ch in "\\/'\"":
209 string += ch
210 else:
211 raise QAPISchemaError(self,
212 "Unknown escape \\%s" %ch)
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200213 esc = False
214 elif ch == "\\":
215 esc = True
216 elif ch == "'":
217 self.val = string
218 return
219 else:
220 string += ch
Fam Zhenge53188a2015-05-04 09:05:18 -0600221 elif self.tok in "tfn":
222 val = self.src[self.cursor - 1:]
223 if val.startswith("true"):
224 self.val = True
225 self.cursor += 3
226 return
227 elif val.startswith("false"):
228 self.val = False
229 self.cursor += 4
230 return
231 elif val.startswith("null"):
232 self.val = None
233 self.cursor += 3
234 return
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200235 elif self.tok == '\n':
236 if self.cursor == len(self.src):
237 self.tok = None
238 return
Wenchao Xia515b9432014-03-04 18:44:33 -0800239 self.line += 1
240 self.line_pos = self.cursor
Markus Armbruster9213aa52013-07-27 17:41:57 +0200241 elif not self.tok.isspace():
242 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
Michael Roth0f923be2011-07-19 14:50:39 -0500243
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200244 def get_members(self):
245 expr = OrderedDict()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200246 if self.tok == '}':
247 self.accept()
248 return expr
249 if self.tok != "'":
250 raise QAPISchemaError(self, 'Expected string or "}"')
251 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200252 key = self.val
253 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200254 if self.tok != ':':
255 raise QAPISchemaError(self, 'Expected ":"')
256 self.accept()
Wenchao Xia4b359912014-03-04 18:44:32 -0800257 if key in expr:
258 raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200259 expr[key] = self.get_expr(True)
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200260 if self.tok == '}':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200261 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200262 return expr
263 if self.tok != ',':
264 raise QAPISchemaError(self, 'Expected "," or "}"')
265 self.accept()
266 if self.tok != "'":
267 raise QAPISchemaError(self, 'Expected string')
Michael Roth0f923be2011-07-19 14:50:39 -0500268
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200269 def get_values(self):
270 expr = []
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200271 if self.tok == ']':
272 self.accept()
273 return expr
Fam Zhenge53188a2015-05-04 09:05:18 -0600274 if not self.tok in "{['tfn":
275 raise QAPISchemaError(self, 'Expected "{", "[", "]", string, '
276 'boolean or "null"')
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200277 while True:
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200278 expr.append(self.get_expr(True))
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200279 if self.tok == ']':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200280 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200281 return expr
282 if self.tok != ',':
283 raise QAPISchemaError(self, 'Expected "," or "]"')
284 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500285
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200286 def get_expr(self, nested):
287 if self.tok != '{' and not nested:
288 raise QAPISchemaError(self, 'Expected "{"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200289 if self.tok == '{':
290 self.accept()
291 expr = self.get_members()
292 elif self.tok == '[':
293 self.accept()
294 expr = self.get_values()
Fam Zhenge53188a2015-05-04 09:05:18 -0600295 elif self.tok in "'tfn":
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200296 expr = self.val
297 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200298 else:
299 raise QAPISchemaError(self, 'Expected "{", "[" or string')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200300 return expr
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200301
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800302def find_base_fields(base):
303 base_struct_define = find_struct(base)
304 if not base_struct_define:
305 return None
306 return base_struct_define['data']
307
Eric Blake811d04f2015-05-04 09:05:10 -0600308# Return the qtype of an alternate branch, or None on error.
309def find_alternate_member_qtype(qapi_type):
Eric Blake44bd1272015-05-04 09:05:08 -0600310 if builtin_types.has_key(qapi_type):
311 return builtin_types[qapi_type]
312 elif find_struct(qapi_type):
313 return "QTYPE_QDICT"
314 elif find_enum(qapi_type):
315 return "QTYPE_QSTRING"
Eric Blake811d04f2015-05-04 09:05:10 -0600316 elif find_union(qapi_type):
317 return "QTYPE_QDICT"
Eric Blake44bd1272015-05-04 09:05:08 -0600318 return None
319
Wenchao Xiabceae762014-03-06 17:08:56 -0800320# Return the discriminator enum define if discriminator is specified as an
321# enum type, otherwise return None.
322def discriminator_find_enum_define(expr):
323 base = expr.get('base')
324 discriminator = expr.get('discriminator')
325
326 if not (discriminator and base):
327 return None
328
329 base_fields = find_base_fields(base)
330 if not base_fields:
331 return None
332
333 discriminator_type = base_fields.get(discriminator)
334 if not discriminator_type:
335 return None
336
337 return find_enum(discriminator_type)
338
Eric Blakec9e0a792015-05-04 09:05:22 -0600339valid_name = re.compile('^[a-zA-Z_][a-zA-Z0-9_.-]*$')
340def check_name(expr_info, source, name, allow_optional = False,
341 enum_member = False):
342 global valid_name
343 membername = name
344
345 if not isinstance(name, str):
346 raise QAPIExprError(expr_info,
347 "%s requires a string name" % source)
348 if name.startswith('*'):
349 membername = name[1:]
350 if not allow_optional:
351 raise QAPIExprError(expr_info,
352 "%s does not allow optional name '%s'"
353 % (source, name))
354 # Enum members can start with a digit, because the generated C
355 # code always prefixes it with the enum name
356 if enum_member:
357 membername = '_' + membername
358 if not valid_name.match(membername):
359 raise QAPIExprError(expr_info,
360 "%s uses invalid name '%s'" % (source, name))
361
Eric Blakedd883c62015-05-04 09:05:21 -0600362def check_type(expr_info, source, value, allow_array = False,
Eric Blake2cbf0992015-05-04 09:05:24 -0600363 allow_dict = False, allow_optional = False,
364 allow_star = False, allow_metas = []):
Eric Blakedd883c62015-05-04 09:05:21 -0600365 global all_names
366 orig_value = value
367
368 if value is None:
369 return
370
Eric Blake2cbf0992015-05-04 09:05:24 -0600371 if allow_star and value == '**':
Eric Blakedd883c62015-05-04 09:05:21 -0600372 return
373
374 # Check if array type for value is okay
375 if isinstance(value, list):
376 if not allow_array:
377 raise QAPIExprError(expr_info,
378 "%s cannot be an array" % source)
379 if len(value) != 1 or not isinstance(value[0], str):
380 raise QAPIExprError(expr_info,
381 "%s: array type must contain single type name"
382 % source)
383 value = value[0]
384 orig_value = "array of %s" %value
385
386 # Check if type name for value is okay
387 if isinstance(value, str):
Eric Blake2cbf0992015-05-04 09:05:24 -0600388 if value == '**':
389 raise QAPIExprError(expr_info,
390 "%s uses '**' but did not request 'gen':false"
391 % source)
Eric Blakedd883c62015-05-04 09:05:21 -0600392 if not value in all_names:
393 raise QAPIExprError(expr_info,
394 "%s uses unknown type '%s'"
395 % (source, orig_value))
396 if not all_names[value] in allow_metas:
397 raise QAPIExprError(expr_info,
398 "%s cannot use %s type '%s'"
399 % (source, all_names[value], orig_value))
400 return
401
402 # value is a dictionary, check that each member is okay
403 if not isinstance(value, OrderedDict):
404 raise QAPIExprError(expr_info,
405 "%s should be a dictionary" % source)
406 if not allow_dict:
407 raise QAPIExprError(expr_info,
408 "%s should be a type name" % source)
409 for (key, arg) in value.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600410 check_name(expr_info, "Member of %s" % source, key,
411 allow_optional=allow_optional)
Eric Blake6b5abc72015-05-04 09:05:33 -0600412 # Todo: allow dictionaries to represent default values of
413 # an optional argument.
Eric Blakedd883c62015-05-04 09:05:21 -0600414 check_type(expr_info, "Member '%s' of %s" % (key, source), arg,
Eric Blake6b5abc72015-05-04 09:05:33 -0600415 allow_array=True, allow_star=allow_star,
Eric Blakedd883c62015-05-04 09:05:21 -0600416 allow_metas=['built-in', 'union', 'alternate', 'struct',
Eric Blake6b5abc72015-05-04 09:05:33 -0600417 'enum'])
Eric Blakedd883c62015-05-04 09:05:21 -0600418
Eric Blakeff55d722015-05-04 09:05:37 -0600419def check_member_clash(expr_info, base_name, data, source = ""):
420 base = find_struct(base_name)
421 assert base
422 base_members = base['data']
423 for key in data.keys():
424 if key.startswith('*'):
425 key = key[1:]
426 if key in base_members or "*" + key in base_members:
427 raise QAPIExprError(expr_info,
428 "Member name '%s'%s clashes with base '%s'"
429 % (key, source, base_name))
430 if base.get('base'):
431 check_member_clash(expr_info, base['base'], data, source)
432
Eric Blakedd883c62015-05-04 09:05:21 -0600433def check_command(expr, expr_info):
434 name = expr['command']
Eric Blake2cbf0992015-05-04 09:05:24 -0600435 allow_star = expr.has_key('gen')
436
Eric Blakedd883c62015-05-04 09:05:21 -0600437 check_type(expr_info, "'data' for command '%s'" % name,
Eric Blakec9e0a792015-05-04 09:05:22 -0600438 expr.get('data'), allow_dict=True, allow_optional=True,
Eric Blake2cbf0992015-05-04 09:05:24 -0600439 allow_metas=['union', 'struct'], allow_star=allow_star)
Eric Blake10d4d992015-05-04 09:05:23 -0600440 returns_meta = ['union', 'struct']
441 if name in returns_whitelist:
442 returns_meta += ['built-in', 'alternate', 'enum']
Eric Blakedd883c62015-05-04 09:05:21 -0600443 check_type(expr_info, "'returns' for command '%s'" % name,
444 expr.get('returns'), allow_array=True, allow_dict=True,
Eric Blake2cbf0992015-05-04 09:05:24 -0600445 allow_optional=True, allow_metas=returns_meta,
446 allow_star=allow_star)
Eric Blakedd883c62015-05-04 09:05:21 -0600447
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200448def check_event(expr, expr_info):
Eric Blake4dc2e692015-05-04 09:05:17 -0600449 global events
450 name = expr['event']
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200451 params = expr.get('data')
Eric Blake4dc2e692015-05-04 09:05:17 -0600452
453 if name.upper() == 'MAX':
454 raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created")
455 events.append(name)
Eric Blakedd883c62015-05-04 09:05:21 -0600456 check_type(expr_info, "'data' for event '%s'" % name,
Eric Blakec9e0a792015-05-04 09:05:22 -0600457 expr.get('data'), allow_dict=True, allow_optional=True,
Eric Blakedd883c62015-05-04 09:05:21 -0600458 allow_metas=['union', 'struct'])
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200459
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800460def check_union(expr, expr_info):
461 name = expr['union']
462 base = expr.get('base')
463 discriminator = expr.get('discriminator')
464 members = expr['data']
Eric Blake44bd1272015-05-04 09:05:08 -0600465 values = { 'MAX': '(automatic)' }
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800466
Eric Blakefd41dd42015-05-04 09:05:25 -0600467 # If the object has a member 'base', its value must name a struct,
Eric Blakea8d4a2e2015-05-04 09:05:07 -0600468 # and there must be a discriminator.
469 if base is not None:
470 if discriminator is None:
471 raise QAPIExprError(expr_info,
472 "Union '%s' requires a discriminator to go "
473 "along with base" %name)
Eric Blake44bd1272015-05-04 09:05:08 -0600474
Eric Blake811d04f2015-05-04 09:05:10 -0600475 # Two types of unions, determined by discriminator.
Eric Blake811d04f2015-05-04 09:05:10 -0600476
477 # With no discriminator it is a simple union.
478 if discriminator is None:
Eric Blake44bd1272015-05-04 09:05:08 -0600479 enum_define = None
Eric Blakedd883c62015-05-04 09:05:21 -0600480 allow_metas=['built-in', 'union', 'alternate', 'struct', 'enum']
Eric Blake44bd1272015-05-04 09:05:08 -0600481 if base is not None:
482 raise QAPIExprError(expr_info,
Eric Blake811d04f2015-05-04 09:05:10 -0600483 "Simple union '%s' must not have a base"
Eric Blake44bd1272015-05-04 09:05:08 -0600484 % name)
485
486 # Else, it's a flat union.
487 else:
488 # The object must have a string member 'base'.
489 if not isinstance(base, str):
490 raise QAPIExprError(expr_info,
491 "Flat union '%s' must have a string base field"
492 % name)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800493 base_fields = find_base_fields(base)
494 if not base_fields:
495 raise QAPIExprError(expr_info,
Eric Blakefd41dd42015-05-04 09:05:25 -0600496 "Base '%s' is not a valid struct"
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800497 % base)
498
Eric Blakec9e0a792015-05-04 09:05:22 -0600499 # The value of member 'discriminator' must name a non-optional
Eric Blakefd41dd42015-05-04 09:05:25 -0600500 # member of the base struct.
Eric Blakec9e0a792015-05-04 09:05:22 -0600501 check_name(expr_info, "Discriminator of flat union '%s'" % name,
502 discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800503 discriminator_type = base_fields.get(discriminator)
504 if not discriminator_type:
505 raise QAPIExprError(expr_info,
506 "Discriminator '%s' is not a member of base "
Eric Blakefd41dd42015-05-04 09:05:25 -0600507 "struct '%s'"
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800508 % (discriminator, base))
509 enum_define = find_enum(discriminator_type)
Eric Blakedd883c62015-05-04 09:05:21 -0600510 allow_metas=['struct']
Wenchao Xia52230702014-03-04 18:44:39 -0800511 # Do not allow string discriminator
512 if not enum_define:
513 raise QAPIExprError(expr_info,
514 "Discriminator '%s' must be of enumeration "
515 "type" % discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800516
517 # Check every branch
518 for (key, value) in members.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600519 check_name(expr_info, "Member of union '%s'" % name, key)
520
Eric Blakedd883c62015-05-04 09:05:21 -0600521 # Each value must name a known type; furthermore, in flat unions,
Eric Blakeff55d722015-05-04 09:05:37 -0600522 # branches must be a struct with no overlapping member names
Eric Blakedd883c62015-05-04 09:05:21 -0600523 check_type(expr_info, "Member '%s' of union '%s'" % (key, name),
524 value, allow_array=True, allow_metas=allow_metas)
Eric Blakeff55d722015-05-04 09:05:37 -0600525 if base:
526 branch_struct = find_struct(value)
527 assert branch_struct
528 check_member_clash(expr_info, base, branch_struct['data'],
529 " of branch '%s'" % key)
Eric Blakedd883c62015-05-04 09:05:21 -0600530
Eric Blake44bd1272015-05-04 09:05:08 -0600531 # If the discriminator names an enum type, then all members
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800532 # of 'data' must also be members of the enum type.
Eric Blake44bd1272015-05-04 09:05:08 -0600533 if enum_define:
534 if not key in enum_define['enum_values']:
535 raise QAPIExprError(expr_info,
536 "Discriminator value '%s' is not found in "
537 "enum '%s'" %
538 (key, enum_define["enum_name"]))
539
540 # Otherwise, check for conflicts in the generated enum
541 else:
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600542 c_key = camel_to_upper(key)
Eric Blake44bd1272015-05-04 09:05:08 -0600543 if c_key in values:
544 raise QAPIExprError(expr_info,
545 "Union '%s' member '%s' clashes with '%s'"
546 % (name, key, values[c_key]))
547 values[c_key] = key
548
Eric Blake811d04f2015-05-04 09:05:10 -0600549def check_alternate(expr, expr_info):
Eric Blakeab916fa2015-05-04 09:05:13 -0600550 name = expr['alternate']
Eric Blake811d04f2015-05-04 09:05:10 -0600551 members = expr['data']
552 values = { 'MAX': '(automatic)' }
553 types_seen = {}
Eric Blake44bd1272015-05-04 09:05:08 -0600554
Eric Blake811d04f2015-05-04 09:05:10 -0600555 # Check every branch
556 for (key, value) in members.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600557 check_name(expr_info, "Member of alternate '%s'" % name, key)
558
Eric Blake811d04f2015-05-04 09:05:10 -0600559 # Check for conflicts in the generated enum
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600560 c_key = camel_to_upper(key)
Eric Blake811d04f2015-05-04 09:05:10 -0600561 if c_key in values:
562 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600563 "Alternate '%s' member '%s' clashes with '%s'"
564 % (name, key, values[c_key]))
Eric Blake811d04f2015-05-04 09:05:10 -0600565 values[c_key] = key
566
567 # Ensure alternates have no type conflicts.
Eric Blakedd883c62015-05-04 09:05:21 -0600568 check_type(expr_info, "Member '%s' of alternate '%s'" % (key, name),
569 value,
570 allow_metas=['built-in', 'union', 'struct', 'enum'])
Eric Blake811d04f2015-05-04 09:05:10 -0600571 qtype = find_alternate_member_qtype(value)
Eric Blakedd883c62015-05-04 09:05:21 -0600572 assert qtype
Eric Blake811d04f2015-05-04 09:05:10 -0600573 if qtype in types_seen:
574 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600575 "Alternate '%s' member '%s' can't "
Eric Blake811d04f2015-05-04 09:05:10 -0600576 "be distinguished from member '%s'"
577 % (name, key, types_seen[qtype]))
578 types_seen[qtype] = key
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800579
Eric Blakecf393592015-05-04 09:05:04 -0600580def check_enum(expr, expr_info):
581 name = expr['enum']
582 members = expr.get('data')
583 values = { 'MAX': '(automatic)' }
584
585 if not isinstance(members, list):
586 raise QAPIExprError(expr_info,
587 "Enum '%s' requires an array for 'data'" % name)
588 for member in members:
Eric Blakec9e0a792015-05-04 09:05:22 -0600589 check_name(expr_info, "Member of enum '%s'" %name, member,
590 enum_member=True)
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600591 key = camel_to_upper(member)
Eric Blakecf393592015-05-04 09:05:04 -0600592 if key in values:
593 raise QAPIExprError(expr_info,
594 "Enum '%s' member '%s' clashes with '%s'"
595 % (name, member, values[key]))
596 values[key] = member
597
Eric Blakedd883c62015-05-04 09:05:21 -0600598def check_struct(expr, expr_info):
Eric Blakefd41dd42015-05-04 09:05:25 -0600599 name = expr['struct']
Eric Blakedd883c62015-05-04 09:05:21 -0600600 members = expr['data']
601
Eric Blakefd41dd42015-05-04 09:05:25 -0600602 check_type(expr_info, "'data' for struct '%s'" % name, members,
Eric Blakec9e0a792015-05-04 09:05:22 -0600603 allow_dict=True, allow_optional=True)
Eric Blakefd41dd42015-05-04 09:05:25 -0600604 check_type(expr_info, "'base' for struct '%s'" % name, expr.get('base'),
Eric Blakedd883c62015-05-04 09:05:21 -0600605 allow_metas=['struct'])
Eric Blakeff55d722015-05-04 09:05:37 -0600606 if expr.get('base'):
607 check_member_clash(expr_info, expr['base'], expr['data'])
Eric Blakedd883c62015-05-04 09:05:21 -0600608
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800609def check_exprs(schema):
610 for expr_elem in schema.exprs:
611 expr = expr_elem['expr']
Eric Blakecf393592015-05-04 09:05:04 -0600612 info = expr_elem['info']
613
614 if expr.has_key('enum'):
615 check_enum(expr, info)
616 elif expr.has_key('union'):
Eric Blakeab916fa2015-05-04 09:05:13 -0600617 check_union(expr, info)
618 elif expr.has_key('alternate'):
619 check_alternate(expr, info)
Eric Blakefd41dd42015-05-04 09:05:25 -0600620 elif expr.has_key('struct'):
Eric Blakedd883c62015-05-04 09:05:21 -0600621 check_struct(expr, info)
622 elif expr.has_key('command'):
623 check_command(expr, info)
Eric Blakecf393592015-05-04 09:05:04 -0600624 elif expr.has_key('event'):
625 check_event(expr, info)
Eric Blakedd883c62015-05-04 09:05:21 -0600626 else:
627 assert False, 'unexpected meta type'
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800628
Eric Blake0545f6b2015-05-04 09:05:15 -0600629def check_keys(expr_elem, meta, required, optional=[]):
630 expr = expr_elem['expr']
631 info = expr_elem['info']
632 name = expr[meta]
633 if not isinstance(name, str):
634 raise QAPIExprError(info,
635 "'%s' key must have a string value" % meta)
636 required = required + [ meta ]
637 for (key, value) in expr.items():
638 if not key in required and not key in optional:
639 raise QAPIExprError(info,
640 "Unknown key '%s' in %s '%s'"
641 % (key, meta, name))
Eric Blake2cbf0992015-05-04 09:05:24 -0600642 if (key == 'gen' or key == 'success-response') and value != False:
643 raise QAPIExprError(info,
644 "'%s' of %s '%s' should only use false value"
645 % (key, meta, name))
Eric Blake0545f6b2015-05-04 09:05:15 -0600646 for key in required:
647 if not expr.has_key(key):
648 raise QAPIExprError(info,
649 "Key '%s' is missing from %s '%s'"
650 % (key, meta, name))
651
652
Lluís Vilanova33aaad52014-05-02 15:52:35 +0200653def parse_schema(input_file):
Eric Blake4dc2e692015-05-04 09:05:17 -0600654 global all_names
655 exprs = []
656
Eric Blake268a1c52015-05-04 09:05:09 -0600657 # First pass: read entire file into memory
Markus Armbruster2caba362013-07-27 17:41:56 +0200658 try:
Lluís Vilanova33aaad52014-05-02 15:52:35 +0200659 schema = QAPISchema(open(input_file, "r"))
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200660 except (QAPISchemaError, QAPIExprError), e:
Markus Armbruster2caba362013-07-27 17:41:56 +0200661 print >>sys.stderr, e
662 exit(1)
663
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800664 try:
Eric Blake0545f6b2015-05-04 09:05:15 -0600665 # Next pass: learn the types and check for valid expression keys. At
666 # this point, top-level 'include' has already been flattened.
Eric Blake4dc2e692015-05-04 09:05:17 -0600667 for builtin in builtin_types.keys():
668 all_names[builtin] = 'built-in'
Eric Blake268a1c52015-05-04 09:05:09 -0600669 for expr_elem in schema.exprs:
670 expr = expr_elem['expr']
Eric Blake4dc2e692015-05-04 09:05:17 -0600671 info = expr_elem['info']
Eric Blake268a1c52015-05-04 09:05:09 -0600672 if expr.has_key('enum'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600673 check_keys(expr_elem, 'enum', ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600674 add_enum(expr['enum'], info, expr['data'])
Eric Blake268a1c52015-05-04 09:05:09 -0600675 elif expr.has_key('union'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600676 check_keys(expr_elem, 'union', ['data'],
677 ['base', 'discriminator'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600678 add_union(expr, info)
Eric Blake0545f6b2015-05-04 09:05:15 -0600679 elif expr.has_key('alternate'):
680 check_keys(expr_elem, 'alternate', ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600681 add_name(expr['alternate'], info, 'alternate')
Eric Blakefd41dd42015-05-04 09:05:25 -0600682 elif expr.has_key('struct'):
683 check_keys(expr_elem, 'struct', ['data'], ['base'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600684 add_struct(expr, info)
Eric Blake0545f6b2015-05-04 09:05:15 -0600685 elif expr.has_key('command'):
686 check_keys(expr_elem, 'command', [],
687 ['data', 'returns', 'gen', 'success-response'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600688 add_name(expr['command'], info, 'command')
Eric Blake0545f6b2015-05-04 09:05:15 -0600689 elif expr.has_key('event'):
690 check_keys(expr_elem, 'event', [], ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600691 add_name(expr['event'], info, 'event')
Eric Blake0545f6b2015-05-04 09:05:15 -0600692 else:
693 raise QAPIExprError(expr_elem['info'],
694 "Expression is missing metatype")
Eric Blake268a1c52015-05-04 09:05:09 -0600695 exprs.append(expr)
696
697 # Try again for hidden UnionKind enum
698 for expr_elem in schema.exprs:
699 expr = expr_elem['expr']
700 if expr.has_key('union'):
701 if not discriminator_find_enum_define(expr):
Eric Blake4dc2e692015-05-04 09:05:17 -0600702 add_enum('%sKind' % expr['union'], expr_elem['info'],
703 implicit=True)
Eric Blakeab916fa2015-05-04 09:05:13 -0600704 elif expr.has_key('alternate'):
Eric Blake4dc2e692015-05-04 09:05:17 -0600705 add_enum('%sKind' % expr['alternate'], expr_elem['info'],
706 implicit=True)
Eric Blake268a1c52015-05-04 09:05:09 -0600707
708 # Final pass - validate that exprs make sense
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800709 check_exprs(schema)
710 except QAPIExprError, e:
711 print >>sys.stderr, e
712 exit(1)
713
Michael Roth0f923be2011-07-19 14:50:39 -0500714 return exprs
715
716def parse_args(typeinfo):
Eric Blakefe2a9302015-05-04 09:05:02 -0600717 if isinstance(typeinfo, str):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200718 struct = find_struct(typeinfo)
719 assert struct != None
720 typeinfo = struct['data']
721
Michael Roth0f923be2011-07-19 14:50:39 -0500722 for member in typeinfo:
723 argname = member
724 argentry = typeinfo[member]
725 optional = False
Michael Roth0f923be2011-07-19 14:50:39 -0500726 if member.startswith('*'):
727 argname = member[1:]
728 optional = True
Eric Blake6b5abc72015-05-04 09:05:33 -0600729 # Todo: allow argentry to be OrderedDict, for providing the
730 # value of an optional argument.
731 yield (argname, argentry, optional)
Michael Roth0f923be2011-07-19 14:50:39 -0500732
Michael Roth0f923be2011-07-19 14:50:39 -0500733def camel_case(name):
734 new_name = ''
735 first = True
736 for ch in name:
737 if ch in ['_', '-']:
738 first = True
739 elif first:
740 new_name += ch.upper()
741 first = False
742 else:
743 new_name += ch.lower()
744 return new_name
745
Markus Armbruster849bc532015-05-14 06:50:53 -0600746# ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
747# ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
748# ENUM24_Name -> ENUM24_NAME
749def camel_to_upper(value):
750 c_fun_str = c_name(value, False)
751 if value.isupper():
752 return c_fun_str
753
754 new_name = ''
755 l = len(c_fun_str)
756 for i in range(l):
757 c = c_fun_str[i]
758 # When c is upper and no "_" appears before, do more checks
759 if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
760 # Case 1: next string is lower
761 # Case 2: previous string is digit
762 if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
763 c_fun_str[i - 1].isdigit():
764 new_name += '_'
765 new_name += c
766 return new_name.lstrip('_').upper()
767
768def c_enum_const(type_name, const_name):
769 return camel_to_upper(type_name + '_' + const_name)
770
Eric Blake18df5152015-05-14 06:50:48 -0600771c_name_trans = string.maketrans('.-', '__')
Markus Armbruster47299262015-05-14 06:50:47 -0600772
Eric Blakec6405b52015-05-14 06:50:55 -0600773# Map @name to a valid C identifier.
774# If @protect, avoid returning certain ticklish identifiers (like
775# C keywords) by prepending "q_".
776#
777# Used for converting 'name' from a 'name':'type' qapi definition
778# into a generated struct member, as well as converting type names
779# into substrings of a generated C function name.
780# '__a.b_c' -> '__a_b_c', 'x-foo' -> 'x_foo'
781# protect=True: 'int' -> 'q_int'; protect=False: 'int' -> 'int'
Eric Blake18df5152015-05-14 06:50:48 -0600782def c_name(name, protect=True):
Blue Swirl427a1a22012-07-30 15:46:55 +0000783 # ANSI X3J11/88-090, 3.1.1
784 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
785 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
786 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
787 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
788 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
789 # ISO/IEC 9899:1999, 6.4.1
790 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
791 # ISO/IEC 9899:2011, 6.4.1
792 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
793 '_Static_assert', '_Thread_local'])
794 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
795 # excluding _.*
796 gcc_words = set(['asm', 'typeof'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400797 # C++ ISO/IEC 14882:2003 2.11
798 cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
799 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
800 'namespace', 'new', 'operator', 'private', 'protected',
801 'public', 'reinterpret_cast', 'static_cast', 'template',
802 'this', 'throw', 'true', 'try', 'typeid', 'typename',
803 'using', 'virtual', 'wchar_t',
804 # alternative representations
805 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
806 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
Paolo Bonzini10577252012-09-19 16:31:07 +0200807 # namespace pollution:
Max Reitz8592a542013-12-20 19:28:18 +0100808 polluted_words = set(['unix', 'errno'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400809 if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
Blue Swirl427a1a22012-07-30 15:46:55 +0000810 return "q_" + name
Eric Blake18df5152015-05-14 06:50:48 -0600811 return name.translate(c_name_trans)
Michael Roth0f923be2011-07-19 14:50:39 -0500812
Eric Blakec6405b52015-05-14 06:50:55 -0600813# Map type @name to the C typedef name for the list form.
814#
815# ['Name'] -> 'NameList', ['x-Foo'] -> 'x_FooList', ['int'] -> 'intList'
Michael Roth0f923be2011-07-19 14:50:39 -0500816def c_list_type(name):
Eric Blakec6405b52015-05-14 06:50:55 -0600817 return type_name(name) + 'List'
Michael Roth0f923be2011-07-19 14:50:39 -0500818
Eric Blakec6405b52015-05-14 06:50:55 -0600819# Map type @value to the C typedef form.
820#
821# Used for converting 'type' from a 'member':'type' qapi definition
822# into the alphanumeric portion of the type for a generated C parameter,
823# as well as generated C function names. See c_type() for the rest of
824# the conversion such as adding '*' on pointer types.
825# 'int' -> 'int', '[x-Foo]' -> 'x_FooList', '__a.b_c' -> '__a_b_c'
Eric Blaked5573442015-05-14 06:50:54 -0600826def type_name(value):
827 if type(value) == list:
828 return c_list_type(value[0])
Eric Blakec6405b52015-05-14 06:50:55 -0600829 if value in builtin_types.keys():
830 return value
831 return c_name(value)
Michael Roth0f923be2011-07-19 14:50:39 -0500832
Eric Blakefd41dd42015-05-04 09:05:25 -0600833def add_name(name, info, meta, implicit = False):
Eric Blake4dc2e692015-05-04 09:05:17 -0600834 global all_names
Eric Blakefd41dd42015-05-04 09:05:25 -0600835 check_name(info, "'%s'" % meta, name)
Eric Blake4dc2e692015-05-04 09:05:17 -0600836 if name in all_names:
837 raise QAPIExprError(info,
838 "%s '%s' is already defined"
839 % (all_names[name], name))
840 if not implicit and name[-4:] == 'Kind':
841 raise QAPIExprError(info,
842 "%s '%s' should not end in 'Kind'"
843 % (meta, name))
844 all_names[name] = meta
Kevin Wolfb35284e2013-07-01 16:31:51 +0200845
Eric Blake4dc2e692015-05-04 09:05:17 -0600846def add_struct(definition, info):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200847 global struct_types
Eric Blakefd41dd42015-05-04 09:05:25 -0600848 name = definition['struct']
849 add_name(name, info, 'struct')
Kevin Wolfb35284e2013-07-01 16:31:51 +0200850 struct_types.append(definition)
851
852def find_struct(name):
853 global struct_types
854 for struct in struct_types:
Eric Blakefd41dd42015-05-04 09:05:25 -0600855 if struct['struct'] == name:
Kevin Wolfb35284e2013-07-01 16:31:51 +0200856 return struct
857 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500858
Eric Blake4dc2e692015-05-04 09:05:17 -0600859def add_union(definition, info):
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200860 global union_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600861 name = definition['union']
862 add_name(name, info, 'union')
Eric Blakeab916fa2015-05-04 09:05:13 -0600863 union_types.append(definition)
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200864
865def find_union(name):
866 global union_types
867 for union in union_types:
868 if union['union'] == name:
869 return union
870 return None
871
Eric Blake4dc2e692015-05-04 09:05:17 -0600872def add_enum(name, info, enum_values = None, implicit = False):
Michael Roth0f923be2011-07-19 14:50:39 -0500873 global enum_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600874 add_name(name, info, 'enum', implicit)
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800875 enum_types.append({"enum_name": name, "enum_values": enum_values})
876
877def find_enum(name):
878 global enum_types
879 for enum in enum_types:
880 if enum['enum_name'] == name:
881 return enum
882 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500883
884def is_enum(name):
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800885 return find_enum(name) != None
Michael Roth0f923be2011-07-19 14:50:39 -0500886
Amos Kong05dfb262014-06-10 19:25:53 +0800887eatspace = '\033EATSPACE.'
Eric Blaked5573442015-05-14 06:50:54 -0600888pointer_suffix = ' *' + eatspace
Amos Kong05dfb262014-06-10 19:25:53 +0800889
Eric Blakec6405b52015-05-14 06:50:55 -0600890# Map type @name to its C type expression.
891# If @is_param, const-qualify the string type.
892#
893# This function is used for computing the full C type of 'member':'name'.
Amos Kong05dfb262014-06-10 19:25:53 +0800894# A special suffix is added in c_type() for pointer types, and it's
895# stripped in mcgen(). So please notice this when you check the return
896# value of c_type() outside mcgen().
Eric Blaked5573442015-05-14 06:50:54 -0600897def c_type(value, is_param=False):
898 if value == 'str':
Amos Kong0d14eeb2014-06-10 19:25:52 +0800899 if is_param:
Eric Blaked5573442015-05-14 06:50:54 -0600900 return 'const char' + pointer_suffix
901 return 'char' + pointer_suffix
Amos Kong05dfb262014-06-10 19:25:53 +0800902
Eric Blaked5573442015-05-14 06:50:54 -0600903 elif value == 'int':
Michael Roth0f923be2011-07-19 14:50:39 -0500904 return 'int64_t'
Eric Blaked5573442015-05-14 06:50:54 -0600905 elif (value == 'int8' or value == 'int16' or value == 'int32' or
906 value == 'int64' or value == 'uint8' or value == 'uint16' or
907 value == 'uint32' or value == 'uint64'):
908 return value + '_t'
909 elif value == 'size':
Laszlo Ersek092705d2012-07-17 16:17:07 +0200910 return 'uint64_t'
Eric Blaked5573442015-05-14 06:50:54 -0600911 elif value == 'bool':
Michael Roth0f923be2011-07-19 14:50:39 -0500912 return 'bool'
Eric Blaked5573442015-05-14 06:50:54 -0600913 elif value == 'number':
Michael Roth0f923be2011-07-19 14:50:39 -0500914 return 'double'
Eric Blaked5573442015-05-14 06:50:54 -0600915 elif type(value) == list:
916 return c_list_type(value[0]) + pointer_suffix
917 elif is_enum(value):
Eric Blakec6405b52015-05-14 06:50:55 -0600918 return c_name(value)
Eric Blaked5573442015-05-14 06:50:54 -0600919 elif value == None:
Michael Roth0f923be2011-07-19 14:50:39 -0500920 return 'void'
Eric Blaked5573442015-05-14 06:50:54 -0600921 elif value in events:
922 return camel_case(value) + 'Event' + pointer_suffix
Michael Roth0f923be2011-07-19 14:50:39 -0500923 else:
Eric Blaked5573442015-05-14 06:50:54 -0600924 # complex type name
925 assert isinstance(value, str) and value != ""
Eric Blakec6405b52015-05-14 06:50:55 -0600926 return c_name(value) + pointer_suffix
Amos Kong05dfb262014-06-10 19:25:53 +0800927
Eric Blaked5573442015-05-14 06:50:54 -0600928def is_c_ptr(value):
929 return c_type(value).endswith(pointer_suffix)
Michael Roth0f923be2011-07-19 14:50:39 -0500930
931def genindent(count):
932 ret = ""
933 for i in range(count):
934 ret += " "
935 return ret
936
937indent_level = 0
938
939def push_indent(indent_amount=4):
940 global indent_level
941 indent_level += indent_amount
942
943def pop_indent(indent_amount=4):
944 global indent_level
945 indent_level -= indent_amount
946
947def cgen(code, **kwds):
948 indent = genindent(indent_level)
949 lines = code.split('\n')
950 lines = map(lambda x: indent + x, lines)
951 return '\n'.join(lines) % kwds + '\n'
952
953def mcgen(code, **kwds):
Amos Kong05dfb262014-06-10 19:25:53 +0800954 raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
955 return re.sub(re.escape(eatspace) + ' *', '', raw)
Michael Roth0f923be2011-07-19 14:50:39 -0500956
957def basename(filename):
958 return filename.split("/")[-1]
959
960def guardname(filename):
Michael Rothd8e1f212011-11-29 16:47:48 -0600961 guard = basename(filename).rsplit(".", 1)[0]
962 for substr in [".", " ", "-"]:
963 guard = guard.replace(substr, "_")
964 return guard.upper() + '_H'
Michael Rothc0afa9c2013-05-10 17:46:00 -0500965
966def guardstart(name):
967 return mcgen('''
968
969#ifndef %(name)s
970#define %(name)s
971
972''',
973 name=guardname(name))
974
975def guardend(name):
976 return mcgen('''
977
978#endif /* %(name)s */
979
980''',
981 name=guardname(name))
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200982
983def parse_command_line(extra_options = "", extra_long_options = []):
984
985 try:
986 opts, args = getopt.gnu_getopt(sys.argv[1:],
Markus Armbruster16d80f62015-04-02 13:32:16 +0200987 "chp:o:" + extra_options,
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200988 ["source", "header", "prefix=",
Markus Armbruster16d80f62015-04-02 13:32:16 +0200989 "output-dir="] + extra_long_options)
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200990 except getopt.GetoptError, err:
Markus Armbrusterb4540962015-04-02 13:17:34 +0200991 print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200992 sys.exit(1)
993
994 output_dir = ""
995 prefix = ""
996 do_c = False
997 do_h = False
998 extra_opts = []
999
1000 for oa in opts:
1001 o, a = oa
1002 if o in ("-p", "--prefix"):
1003 prefix = a
Markus Armbruster2114f5a2015-04-02 13:12:21 +02001004 elif o in ("-o", "--output-dir"):
1005 output_dir = a + "/"
1006 elif o in ("-c", "--source"):
1007 do_c = True
1008 elif o in ("-h", "--header"):
1009 do_h = True
1010 else:
1011 extra_opts.append(oa)
1012
1013 if not do_c and not do_h:
1014 do_c = True
1015 do_h = True
1016
Markus Armbruster16d80f62015-04-02 13:32:16 +02001017 if len(args) != 1:
1018 print >>sys.stderr, "%s: need exactly one argument" % sys.argv[0]
Markus Armbrusterb4540962015-04-02 13:17:34 +02001019 sys.exit(1)
Markus Armbruster16d80f62015-04-02 13:32:16 +02001020 input_file = args[0]
Markus Armbrusterb4540962015-04-02 13:17:34 +02001021
Markus Armbruster2114f5a2015-04-02 13:12:21 +02001022 return (input_file, output_dir, do_c, do_h, prefix, extra_opts)