blob: c2eb12ba3a49cc956bc1f028b87a878bbff6aef5 [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 Armbruster54414042015-06-09 16:22:45 +0200104 def __init__(self, fp, fname = None, include_hist = [],
105 previously_included = [], incl_info = None):
Benoît Canet24fd8482014-05-16 12:51:56 +0200106 """ include_hist is a stack used to detect inclusion cycles
107 previously_included is a global state used to avoid multiple
108 inclusions of the same file"""
Markus Armbruster54414042015-06-09 16:22:45 +0200109 abs_fname = os.path.abspath(fp.name)
110 if fname is None:
111 fname = fp.name
112 self.fname = fname
113 self.include_hist = include_hist + [(fname, abs_fname)]
114 previously_included.append(abs_fname)
115 self.incl_info = incl_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:
Markus Armbruster54414042015-06-09 16:22:45 +0200126 expr_info = {'file': fname, 'line': self.line,
127 'parent': self.incl_info}
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200128 expr = self.get_expr(False)
129 if isinstance(expr, dict) and "include" in expr:
130 if len(expr) != 1:
131 raise QAPIExprError(expr_info, "Invalid 'include' directive")
132 include = expr["include"]
133 if not isinstance(include, str):
134 raise QAPIExprError(expr_info,
135 'Expected a file name (string), got: %s'
136 % include)
Markus Armbruster54414042015-06-09 16:22:45 +0200137 incl_abs_fname = os.path.join(os.path.dirname(abs_fname),
138 include)
Stefan Hajnoczi7ac9a9d2014-08-27 12:08:51 +0100139 for elem in self.include_hist:
Markus Armbruster54414042015-06-09 16:22:45 +0200140 if incl_abs_fname == elem[1]:
Stefan Hajnoczi7ac9a9d2014-08-27 12:08:51 +0100141 raise QAPIExprError(expr_info, "Inclusion loop for %s"
142 % include)
Benoît Canet24fd8482014-05-16 12:51:56 +0200143 # skip multiple include of the same file
Markus Armbruster54414042015-06-09 16:22:45 +0200144 if incl_abs_fname in previously_included:
Benoît Canet24fd8482014-05-16 12:51:56 +0200145 continue
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200146 try:
Markus Armbruster54414042015-06-09 16:22:45 +0200147 fobj = open(incl_abs_fname, 'r')
Luiz Capitulino34788812014-05-20 13:50:19 -0400148 except IOError, e:
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200149 raise QAPIExprError(expr_info,
150 '%s: %s' % (e.strerror, include))
Benoît Canet24fd8482014-05-16 12:51:56 +0200151 exprs_include = QAPISchema(fobj, include, self.include_hist,
152 previously_included, expr_info)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200153 self.exprs.extend(exprs_include.exprs)
154 else:
155 expr_elem = {'expr': expr,
156 'info': expr_info}
157 self.exprs.append(expr_elem)
Michael Roth0f923be2011-07-19 14:50:39 -0500158
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200159 def accept(self):
160 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200161 self.tok = self.src[self.cursor]
Markus Armbruster2caba362013-07-27 17:41:56 +0200162 self.pos = self.cursor
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200163 self.cursor += 1
164 self.val = None
Michael Roth0f923be2011-07-19 14:50:39 -0500165
Markus Armbrusterf1a145e2013-07-27 17:42:01 +0200166 if self.tok == '#':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200167 self.cursor = self.src.find('\n', self.cursor)
168 elif self.tok in ['{', '}', ':', ',', '[', ']']:
169 return
170 elif self.tok == "'":
171 string = ''
172 esc = False
173 while True:
174 ch = self.src[self.cursor]
175 self.cursor += 1
176 if ch == '\n':
Markus Armbruster2caba362013-07-27 17:41:56 +0200177 raise QAPISchemaError(self,
178 'Missing terminating "\'"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200179 if esc:
Eric Blakea7f59662015-05-04 09:05:36 -0600180 if ch == 'b':
181 string += '\b'
182 elif ch == 'f':
183 string += '\f'
184 elif ch == 'n':
185 string += '\n'
186 elif ch == 'r':
187 string += '\r'
188 elif ch == 't':
189 string += '\t'
190 elif ch == 'u':
191 value = 0
192 for x in range(0, 4):
193 ch = self.src[self.cursor]
194 self.cursor += 1
195 if ch not in "0123456789abcdefABCDEF":
196 raise QAPISchemaError(self,
197 '\\u escape needs 4 '
198 'hex digits')
199 value = (value << 4) + int(ch, 16)
200 # If Python 2 and 3 didn't disagree so much on
201 # how to handle Unicode, then we could allow
202 # Unicode string defaults. But most of QAPI is
203 # ASCII-only, so we aren't losing much for now.
204 if not value or value > 0x7f:
205 raise QAPISchemaError(self,
206 'For now, \\u escape '
207 'only supports non-zero '
208 'values up to \\u007f')
209 string += chr(value)
210 elif ch in "\\/'\"":
211 string += ch
212 else:
213 raise QAPISchemaError(self,
214 "Unknown escape \\%s" %ch)
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200215 esc = False
216 elif ch == "\\":
217 esc = True
218 elif ch == "'":
219 self.val = string
220 return
221 else:
222 string += ch
Fam Zhenge53188a2015-05-04 09:05:18 -0600223 elif self.tok in "tfn":
224 val = self.src[self.cursor - 1:]
225 if val.startswith("true"):
226 self.val = True
227 self.cursor += 3
228 return
229 elif val.startswith("false"):
230 self.val = False
231 self.cursor += 4
232 return
233 elif val.startswith("null"):
234 self.val = None
235 self.cursor += 3
236 return
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200237 elif self.tok == '\n':
238 if self.cursor == len(self.src):
239 self.tok = None
240 return
Wenchao Xia515b9432014-03-04 18:44:33 -0800241 self.line += 1
242 self.line_pos = self.cursor
Markus Armbruster9213aa52013-07-27 17:41:57 +0200243 elif not self.tok.isspace():
244 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
Michael Roth0f923be2011-07-19 14:50:39 -0500245
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200246 def get_members(self):
247 expr = OrderedDict()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200248 if self.tok == '}':
249 self.accept()
250 return expr
251 if self.tok != "'":
252 raise QAPISchemaError(self, 'Expected string or "}"')
253 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200254 key = self.val
255 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200256 if self.tok != ':':
257 raise QAPISchemaError(self, 'Expected ":"')
258 self.accept()
Wenchao Xia4b359912014-03-04 18:44:32 -0800259 if key in expr:
260 raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200261 expr[key] = self.get_expr(True)
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200262 if self.tok == '}':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200263 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200264 return expr
265 if self.tok != ',':
266 raise QAPISchemaError(self, 'Expected "," or "}"')
267 self.accept()
268 if self.tok != "'":
269 raise QAPISchemaError(self, 'Expected string')
Michael Roth0f923be2011-07-19 14:50:39 -0500270
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200271 def get_values(self):
272 expr = []
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200273 if self.tok == ']':
274 self.accept()
275 return expr
Fam Zhenge53188a2015-05-04 09:05:18 -0600276 if not self.tok in "{['tfn":
277 raise QAPISchemaError(self, 'Expected "{", "[", "]", string, '
278 'boolean or "null"')
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200279 while True:
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200280 expr.append(self.get_expr(True))
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200281 if self.tok == ']':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200282 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200283 return expr
284 if self.tok != ',':
285 raise QAPISchemaError(self, 'Expected "," or "]"')
286 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500287
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200288 def get_expr(self, nested):
289 if self.tok != '{' and not nested:
290 raise QAPISchemaError(self, 'Expected "{"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200291 if self.tok == '{':
292 self.accept()
293 expr = self.get_members()
294 elif self.tok == '[':
295 self.accept()
296 expr = self.get_values()
Fam Zhenge53188a2015-05-04 09:05:18 -0600297 elif self.tok in "'tfn":
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200298 expr = self.val
299 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200300 else:
301 raise QAPISchemaError(self, 'Expected "{", "[" or string')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200302 return expr
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200303
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800304def find_base_fields(base):
305 base_struct_define = find_struct(base)
306 if not base_struct_define:
307 return None
308 return base_struct_define['data']
309
Eric Blake811d04f2015-05-04 09:05:10 -0600310# Return the qtype of an alternate branch, or None on error.
311def find_alternate_member_qtype(qapi_type):
Eric Blake44bd1272015-05-04 09:05:08 -0600312 if builtin_types.has_key(qapi_type):
313 return builtin_types[qapi_type]
314 elif find_struct(qapi_type):
315 return "QTYPE_QDICT"
316 elif find_enum(qapi_type):
317 return "QTYPE_QSTRING"
Eric Blake811d04f2015-05-04 09:05:10 -0600318 elif find_union(qapi_type):
319 return "QTYPE_QDICT"
Eric Blake44bd1272015-05-04 09:05:08 -0600320 return None
321
Wenchao Xiabceae762014-03-06 17:08:56 -0800322# Return the discriminator enum define if discriminator is specified as an
323# enum type, otherwise return None.
324def discriminator_find_enum_define(expr):
325 base = expr.get('base')
326 discriminator = expr.get('discriminator')
327
328 if not (discriminator and base):
329 return None
330
331 base_fields = find_base_fields(base)
332 if not base_fields:
333 return None
334
335 discriminator_type = base_fields.get(discriminator)
336 if not discriminator_type:
337 return None
338
339 return find_enum(discriminator_type)
340
Eric Blakec9e0a792015-05-04 09:05:22 -0600341valid_name = re.compile('^[a-zA-Z_][a-zA-Z0-9_.-]*$')
342def check_name(expr_info, source, name, allow_optional = False,
343 enum_member = False):
344 global valid_name
345 membername = name
346
347 if not isinstance(name, str):
348 raise QAPIExprError(expr_info,
349 "%s requires a string name" % source)
350 if name.startswith('*'):
351 membername = name[1:]
352 if not allow_optional:
353 raise QAPIExprError(expr_info,
354 "%s does not allow optional name '%s'"
355 % (source, name))
356 # Enum members can start with a digit, because the generated C
357 # code always prefixes it with the enum name
358 if enum_member:
359 membername = '_' + membername
360 if not valid_name.match(membername):
361 raise QAPIExprError(expr_info,
362 "%s uses invalid name '%s'" % (source, name))
363
Eric Blakedd883c62015-05-04 09:05:21 -0600364def check_type(expr_info, source, value, allow_array = False,
Eric Blake2cbf0992015-05-04 09:05:24 -0600365 allow_dict = False, allow_optional = False,
366 allow_star = False, allow_metas = []):
Eric Blakedd883c62015-05-04 09:05:21 -0600367 global all_names
368 orig_value = value
369
370 if value is None:
371 return
372
Eric Blake2cbf0992015-05-04 09:05:24 -0600373 if allow_star and value == '**':
Eric Blakedd883c62015-05-04 09:05:21 -0600374 return
375
376 # Check if array type for value is okay
377 if isinstance(value, list):
378 if not allow_array:
379 raise QAPIExprError(expr_info,
380 "%s cannot be an array" % source)
381 if len(value) != 1 or not isinstance(value[0], str):
382 raise QAPIExprError(expr_info,
383 "%s: array type must contain single type name"
384 % source)
385 value = value[0]
386 orig_value = "array of %s" %value
387
388 # Check if type name for value is okay
389 if isinstance(value, str):
Eric Blake2cbf0992015-05-04 09:05:24 -0600390 if value == '**':
391 raise QAPIExprError(expr_info,
392 "%s uses '**' but did not request 'gen':false"
393 % source)
Eric Blakedd883c62015-05-04 09:05:21 -0600394 if not value in all_names:
395 raise QAPIExprError(expr_info,
396 "%s uses unknown type '%s'"
397 % (source, orig_value))
398 if not all_names[value] in allow_metas:
399 raise QAPIExprError(expr_info,
400 "%s cannot use %s type '%s'"
401 % (source, all_names[value], orig_value))
402 return
403
404 # value is a dictionary, check that each member is okay
405 if not isinstance(value, OrderedDict):
406 raise QAPIExprError(expr_info,
407 "%s should be a dictionary" % source)
408 if not allow_dict:
409 raise QAPIExprError(expr_info,
410 "%s should be a type name" % source)
411 for (key, arg) in value.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600412 check_name(expr_info, "Member of %s" % source, key,
413 allow_optional=allow_optional)
Eric Blake6b5abc72015-05-04 09:05:33 -0600414 # Todo: allow dictionaries to represent default values of
415 # an optional argument.
Eric Blakedd883c62015-05-04 09:05:21 -0600416 check_type(expr_info, "Member '%s' of %s" % (key, source), arg,
Eric Blake6b5abc72015-05-04 09:05:33 -0600417 allow_array=True, allow_star=allow_star,
Eric Blakedd883c62015-05-04 09:05:21 -0600418 allow_metas=['built-in', 'union', 'alternate', 'struct',
Eric Blake6b5abc72015-05-04 09:05:33 -0600419 'enum'])
Eric Blakedd883c62015-05-04 09:05:21 -0600420
Eric Blakeff55d722015-05-04 09:05:37 -0600421def check_member_clash(expr_info, base_name, data, source = ""):
422 base = find_struct(base_name)
423 assert base
424 base_members = base['data']
425 for key in data.keys():
426 if key.startswith('*'):
427 key = key[1:]
428 if key in base_members or "*" + key in base_members:
429 raise QAPIExprError(expr_info,
430 "Member name '%s'%s clashes with base '%s'"
431 % (key, source, base_name))
432 if base.get('base'):
433 check_member_clash(expr_info, base['base'], data, source)
434
Eric Blakedd883c62015-05-04 09:05:21 -0600435def check_command(expr, expr_info):
436 name = expr['command']
Eric Blake2cbf0992015-05-04 09:05:24 -0600437 allow_star = expr.has_key('gen')
438
Eric Blakedd883c62015-05-04 09:05:21 -0600439 check_type(expr_info, "'data' for command '%s'" % name,
Eric Blakec9e0a792015-05-04 09:05:22 -0600440 expr.get('data'), allow_dict=True, allow_optional=True,
Eric Blake2cbf0992015-05-04 09:05:24 -0600441 allow_metas=['union', 'struct'], allow_star=allow_star)
Eric Blake10d4d992015-05-04 09:05:23 -0600442 returns_meta = ['union', 'struct']
443 if name in returns_whitelist:
444 returns_meta += ['built-in', 'alternate', 'enum']
Eric Blakedd883c62015-05-04 09:05:21 -0600445 check_type(expr_info, "'returns' for command '%s'" % name,
446 expr.get('returns'), allow_array=True, allow_dict=True,
Eric Blake2cbf0992015-05-04 09:05:24 -0600447 allow_optional=True, allow_metas=returns_meta,
448 allow_star=allow_star)
Eric Blakedd883c62015-05-04 09:05:21 -0600449
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200450def check_event(expr, expr_info):
Eric Blake4dc2e692015-05-04 09:05:17 -0600451 global events
452 name = expr['event']
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200453 params = expr.get('data')
Eric Blake4dc2e692015-05-04 09:05:17 -0600454
455 if name.upper() == 'MAX':
456 raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created")
457 events.append(name)
Eric Blakedd883c62015-05-04 09:05:21 -0600458 check_type(expr_info, "'data' for event '%s'" % name,
Eric Blakec9e0a792015-05-04 09:05:22 -0600459 expr.get('data'), allow_dict=True, allow_optional=True,
Eric Blakedd883c62015-05-04 09:05:21 -0600460 allow_metas=['union', 'struct'])
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200461
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800462def check_union(expr, expr_info):
463 name = expr['union']
464 base = expr.get('base')
465 discriminator = expr.get('discriminator')
466 members = expr['data']
Eric Blake44bd1272015-05-04 09:05:08 -0600467 values = { 'MAX': '(automatic)' }
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800468
Eric Blakefd41dd42015-05-04 09:05:25 -0600469 # If the object has a member 'base', its value must name a struct,
Eric Blakea8d4a2e2015-05-04 09:05:07 -0600470 # and there must be a discriminator.
471 if base is not None:
472 if discriminator is None:
473 raise QAPIExprError(expr_info,
474 "Union '%s' requires a discriminator to go "
475 "along with base" %name)
Eric Blake44bd1272015-05-04 09:05:08 -0600476
Eric Blake811d04f2015-05-04 09:05:10 -0600477 # Two types of unions, determined by discriminator.
Eric Blake811d04f2015-05-04 09:05:10 -0600478
479 # With no discriminator it is a simple union.
480 if discriminator is None:
Eric Blake44bd1272015-05-04 09:05:08 -0600481 enum_define = None
Eric Blakedd883c62015-05-04 09:05:21 -0600482 allow_metas=['built-in', 'union', 'alternate', 'struct', 'enum']
Eric Blake44bd1272015-05-04 09:05:08 -0600483 if base is not None:
484 raise QAPIExprError(expr_info,
Eric Blake811d04f2015-05-04 09:05:10 -0600485 "Simple union '%s' must not have a base"
Eric Blake44bd1272015-05-04 09:05:08 -0600486 % name)
487
488 # Else, it's a flat union.
489 else:
490 # The object must have a string member 'base'.
491 if not isinstance(base, str):
492 raise QAPIExprError(expr_info,
493 "Flat union '%s' must have a string base field"
494 % name)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800495 base_fields = find_base_fields(base)
496 if not base_fields:
497 raise QAPIExprError(expr_info,
Eric Blakefd41dd42015-05-04 09:05:25 -0600498 "Base '%s' is not a valid struct"
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800499 % base)
500
Eric Blakec9e0a792015-05-04 09:05:22 -0600501 # The value of member 'discriminator' must name a non-optional
Eric Blakefd41dd42015-05-04 09:05:25 -0600502 # member of the base struct.
Eric Blakec9e0a792015-05-04 09:05:22 -0600503 check_name(expr_info, "Discriminator of flat union '%s'" % name,
504 discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800505 discriminator_type = base_fields.get(discriminator)
506 if not discriminator_type:
507 raise QAPIExprError(expr_info,
508 "Discriminator '%s' is not a member of base "
Eric Blakefd41dd42015-05-04 09:05:25 -0600509 "struct '%s'"
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800510 % (discriminator, base))
511 enum_define = find_enum(discriminator_type)
Eric Blakedd883c62015-05-04 09:05:21 -0600512 allow_metas=['struct']
Wenchao Xia52230702014-03-04 18:44:39 -0800513 # Do not allow string discriminator
514 if not enum_define:
515 raise QAPIExprError(expr_info,
516 "Discriminator '%s' must be of enumeration "
517 "type" % discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800518
519 # Check every branch
520 for (key, value) in members.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600521 check_name(expr_info, "Member of union '%s'" % name, key)
522
Eric Blakedd883c62015-05-04 09:05:21 -0600523 # Each value must name a known type; furthermore, in flat unions,
Eric Blakeff55d722015-05-04 09:05:37 -0600524 # branches must be a struct with no overlapping member names
Eric Blakedd883c62015-05-04 09:05:21 -0600525 check_type(expr_info, "Member '%s' of union '%s'" % (key, name),
526 value, allow_array=True, allow_metas=allow_metas)
Eric Blakeff55d722015-05-04 09:05:37 -0600527 if base:
528 branch_struct = find_struct(value)
529 assert branch_struct
530 check_member_clash(expr_info, base, branch_struct['data'],
531 " of branch '%s'" % key)
Eric Blakedd883c62015-05-04 09:05:21 -0600532
Eric Blake44bd1272015-05-04 09:05:08 -0600533 # If the discriminator names an enum type, then all members
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800534 # of 'data' must also be members of the enum type.
Eric Blake44bd1272015-05-04 09:05:08 -0600535 if enum_define:
536 if not key in enum_define['enum_values']:
537 raise QAPIExprError(expr_info,
538 "Discriminator value '%s' is not found in "
539 "enum '%s'" %
540 (key, enum_define["enum_name"]))
541
542 # Otherwise, check for conflicts in the generated enum
543 else:
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600544 c_key = camel_to_upper(key)
Eric Blake44bd1272015-05-04 09:05:08 -0600545 if c_key in values:
546 raise QAPIExprError(expr_info,
547 "Union '%s' member '%s' clashes with '%s'"
548 % (name, key, values[c_key]))
549 values[c_key] = key
550
Eric Blake811d04f2015-05-04 09:05:10 -0600551def check_alternate(expr, expr_info):
Eric Blakeab916fa2015-05-04 09:05:13 -0600552 name = expr['alternate']
Eric Blake811d04f2015-05-04 09:05:10 -0600553 members = expr['data']
554 values = { 'MAX': '(automatic)' }
555 types_seen = {}
Eric Blake44bd1272015-05-04 09:05:08 -0600556
Eric Blake811d04f2015-05-04 09:05:10 -0600557 # Check every branch
558 for (key, value) in members.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600559 check_name(expr_info, "Member of alternate '%s'" % name, key)
560
Eric Blake811d04f2015-05-04 09:05:10 -0600561 # Check for conflicts in the generated enum
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600562 c_key = camel_to_upper(key)
Eric Blake811d04f2015-05-04 09:05:10 -0600563 if c_key in values:
564 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600565 "Alternate '%s' member '%s' clashes with '%s'"
566 % (name, key, values[c_key]))
Eric Blake811d04f2015-05-04 09:05:10 -0600567 values[c_key] = key
568
569 # Ensure alternates have no type conflicts.
Eric Blakedd883c62015-05-04 09:05:21 -0600570 check_type(expr_info, "Member '%s' of alternate '%s'" % (key, name),
571 value,
572 allow_metas=['built-in', 'union', 'struct', 'enum'])
Eric Blake811d04f2015-05-04 09:05:10 -0600573 qtype = find_alternate_member_qtype(value)
Eric Blakedd883c62015-05-04 09:05:21 -0600574 assert qtype
Eric Blake811d04f2015-05-04 09:05:10 -0600575 if qtype in types_seen:
576 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600577 "Alternate '%s' member '%s' can't "
Eric Blake811d04f2015-05-04 09:05:10 -0600578 "be distinguished from member '%s'"
579 % (name, key, types_seen[qtype]))
580 types_seen[qtype] = key
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800581
Eric Blakecf393592015-05-04 09:05:04 -0600582def check_enum(expr, expr_info):
583 name = expr['enum']
584 members = expr.get('data')
585 values = { 'MAX': '(automatic)' }
586
587 if not isinstance(members, list):
588 raise QAPIExprError(expr_info,
589 "Enum '%s' requires an array for 'data'" % name)
590 for member in members:
Eric Blakec9e0a792015-05-04 09:05:22 -0600591 check_name(expr_info, "Member of enum '%s'" %name, member,
592 enum_member=True)
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600593 key = camel_to_upper(member)
Eric Blakecf393592015-05-04 09:05:04 -0600594 if key in values:
595 raise QAPIExprError(expr_info,
596 "Enum '%s' member '%s' clashes with '%s'"
597 % (name, member, values[key]))
598 values[key] = member
599
Eric Blakedd883c62015-05-04 09:05:21 -0600600def check_struct(expr, expr_info):
Eric Blakefd41dd42015-05-04 09:05:25 -0600601 name = expr['struct']
Eric Blakedd883c62015-05-04 09:05:21 -0600602 members = expr['data']
603
Eric Blakefd41dd42015-05-04 09:05:25 -0600604 check_type(expr_info, "'data' for struct '%s'" % name, members,
Eric Blakec9e0a792015-05-04 09:05:22 -0600605 allow_dict=True, allow_optional=True)
Eric Blakefd41dd42015-05-04 09:05:25 -0600606 check_type(expr_info, "'base' for struct '%s'" % name, expr.get('base'),
Eric Blakedd883c62015-05-04 09:05:21 -0600607 allow_metas=['struct'])
Eric Blakeff55d722015-05-04 09:05:37 -0600608 if expr.get('base'):
609 check_member_clash(expr_info, expr['base'], expr['data'])
Eric Blakedd883c62015-05-04 09:05:21 -0600610
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800611def check_exprs(schema):
612 for expr_elem in schema.exprs:
613 expr = expr_elem['expr']
Eric Blakecf393592015-05-04 09:05:04 -0600614 info = expr_elem['info']
615
616 if expr.has_key('enum'):
617 check_enum(expr, info)
618 elif expr.has_key('union'):
Eric Blakeab916fa2015-05-04 09:05:13 -0600619 check_union(expr, info)
620 elif expr.has_key('alternate'):
621 check_alternate(expr, info)
Eric Blakefd41dd42015-05-04 09:05:25 -0600622 elif expr.has_key('struct'):
Eric Blakedd883c62015-05-04 09:05:21 -0600623 check_struct(expr, info)
624 elif expr.has_key('command'):
625 check_command(expr, info)
Eric Blakecf393592015-05-04 09:05:04 -0600626 elif expr.has_key('event'):
627 check_event(expr, info)
Eric Blakedd883c62015-05-04 09:05:21 -0600628 else:
629 assert False, 'unexpected meta type'
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800630
Eric Blake0545f6b2015-05-04 09:05:15 -0600631def check_keys(expr_elem, meta, required, optional=[]):
632 expr = expr_elem['expr']
633 info = expr_elem['info']
634 name = expr[meta]
635 if not isinstance(name, str):
636 raise QAPIExprError(info,
637 "'%s' key must have a string value" % meta)
638 required = required + [ meta ]
639 for (key, value) in expr.items():
640 if not key in required and not key in optional:
641 raise QAPIExprError(info,
642 "Unknown key '%s' in %s '%s'"
643 % (key, meta, name))
Eric Blake2cbf0992015-05-04 09:05:24 -0600644 if (key == 'gen' or key == 'success-response') and value != False:
645 raise QAPIExprError(info,
646 "'%s' of %s '%s' should only use false value"
647 % (key, meta, name))
Eric Blake0545f6b2015-05-04 09:05:15 -0600648 for key in required:
649 if not expr.has_key(key):
650 raise QAPIExprError(info,
651 "Key '%s' is missing from %s '%s'"
652 % (key, meta, name))
653
654
Markus Armbruster54414042015-06-09 16:22:45 +0200655def parse_schema(fname):
Eric Blake4dc2e692015-05-04 09:05:17 -0600656 global all_names
657 exprs = []
658
Eric Blake268a1c52015-05-04 09:05:09 -0600659 # First pass: read entire file into memory
Markus Armbruster2caba362013-07-27 17:41:56 +0200660 try:
Markus Armbruster54414042015-06-09 16:22:45 +0200661 schema = QAPISchema(open(fname, "r"))
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200662 except (QAPISchemaError, QAPIExprError), e:
Markus Armbruster2caba362013-07-27 17:41:56 +0200663 print >>sys.stderr, e
664 exit(1)
665
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800666 try:
Eric Blake0545f6b2015-05-04 09:05:15 -0600667 # Next pass: learn the types and check for valid expression keys. At
668 # this point, top-level 'include' has already been flattened.
Eric Blake4dc2e692015-05-04 09:05:17 -0600669 for builtin in builtin_types.keys():
670 all_names[builtin] = 'built-in'
Eric Blake268a1c52015-05-04 09:05:09 -0600671 for expr_elem in schema.exprs:
672 expr = expr_elem['expr']
Eric Blake4dc2e692015-05-04 09:05:17 -0600673 info = expr_elem['info']
Eric Blake268a1c52015-05-04 09:05:09 -0600674 if expr.has_key('enum'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600675 check_keys(expr_elem, 'enum', ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600676 add_enum(expr['enum'], info, expr['data'])
Eric Blake268a1c52015-05-04 09:05:09 -0600677 elif expr.has_key('union'):
Eric Blake0545f6b2015-05-04 09:05:15 -0600678 check_keys(expr_elem, 'union', ['data'],
679 ['base', 'discriminator'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600680 add_union(expr, info)
Eric Blake0545f6b2015-05-04 09:05:15 -0600681 elif expr.has_key('alternate'):
682 check_keys(expr_elem, 'alternate', ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600683 add_name(expr['alternate'], info, 'alternate')
Eric Blakefd41dd42015-05-04 09:05:25 -0600684 elif expr.has_key('struct'):
685 check_keys(expr_elem, 'struct', ['data'], ['base'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600686 add_struct(expr, info)
Eric Blake0545f6b2015-05-04 09:05:15 -0600687 elif expr.has_key('command'):
688 check_keys(expr_elem, 'command', [],
689 ['data', 'returns', 'gen', 'success-response'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600690 add_name(expr['command'], info, 'command')
Eric Blake0545f6b2015-05-04 09:05:15 -0600691 elif expr.has_key('event'):
692 check_keys(expr_elem, 'event', [], ['data'])
Eric Blake4dc2e692015-05-04 09:05:17 -0600693 add_name(expr['event'], info, 'event')
Eric Blake0545f6b2015-05-04 09:05:15 -0600694 else:
695 raise QAPIExprError(expr_elem['info'],
696 "Expression is missing metatype")
Eric Blake268a1c52015-05-04 09:05:09 -0600697 exprs.append(expr)
698
699 # Try again for hidden UnionKind enum
700 for expr_elem in schema.exprs:
701 expr = expr_elem['expr']
702 if expr.has_key('union'):
703 if not discriminator_find_enum_define(expr):
Eric Blake4dc2e692015-05-04 09:05:17 -0600704 add_enum('%sKind' % expr['union'], expr_elem['info'],
705 implicit=True)
Eric Blakeab916fa2015-05-04 09:05:13 -0600706 elif expr.has_key('alternate'):
Eric Blake4dc2e692015-05-04 09:05:17 -0600707 add_enum('%sKind' % expr['alternate'], expr_elem['info'],
708 implicit=True)
Eric Blake268a1c52015-05-04 09:05:09 -0600709
710 # Final pass - validate that exprs make sense
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800711 check_exprs(schema)
712 except QAPIExprError, e:
713 print >>sys.stderr, e
714 exit(1)
715
Michael Roth0f923be2011-07-19 14:50:39 -0500716 return exprs
717
718def parse_args(typeinfo):
Eric Blakefe2a9302015-05-04 09:05:02 -0600719 if isinstance(typeinfo, str):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200720 struct = find_struct(typeinfo)
721 assert struct != None
722 typeinfo = struct['data']
723
Michael Roth0f923be2011-07-19 14:50:39 -0500724 for member in typeinfo:
725 argname = member
726 argentry = typeinfo[member]
727 optional = False
Michael Roth0f923be2011-07-19 14:50:39 -0500728 if member.startswith('*'):
729 argname = member[1:]
730 optional = True
Eric Blake6b5abc72015-05-04 09:05:33 -0600731 # Todo: allow argentry to be OrderedDict, for providing the
732 # value of an optional argument.
733 yield (argname, argentry, optional)
Michael Roth0f923be2011-07-19 14:50:39 -0500734
Michael Roth0f923be2011-07-19 14:50:39 -0500735def camel_case(name):
736 new_name = ''
737 first = True
738 for ch in name:
739 if ch in ['_', '-']:
740 first = True
741 elif first:
742 new_name += ch.upper()
743 first = False
744 else:
745 new_name += ch.lower()
746 return new_name
747
Markus Armbruster849bc532015-05-14 06:50:53 -0600748# ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
749# ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
750# ENUM24_Name -> ENUM24_NAME
751def camel_to_upper(value):
752 c_fun_str = c_name(value, False)
753 if value.isupper():
754 return c_fun_str
755
756 new_name = ''
757 l = len(c_fun_str)
758 for i in range(l):
759 c = c_fun_str[i]
760 # When c is upper and no "_" appears before, do more checks
761 if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
762 # Case 1: next string is lower
763 # Case 2: previous string is digit
764 if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
765 c_fun_str[i - 1].isdigit():
766 new_name += '_'
767 new_name += c
768 return new_name.lstrip('_').upper()
769
770def c_enum_const(type_name, const_name):
771 return camel_to_upper(type_name + '_' + const_name)
772
Eric Blake18df5152015-05-14 06:50:48 -0600773c_name_trans = string.maketrans('.-', '__')
Markus Armbruster47299262015-05-14 06:50:47 -0600774
Eric Blakec6405b52015-05-14 06:50:55 -0600775# Map @name to a valid C identifier.
776# If @protect, avoid returning certain ticklish identifiers (like
777# C keywords) by prepending "q_".
778#
779# Used for converting 'name' from a 'name':'type' qapi definition
780# into a generated struct member, as well as converting type names
781# into substrings of a generated C function name.
782# '__a.b_c' -> '__a_b_c', 'x-foo' -> 'x_foo'
783# protect=True: 'int' -> 'q_int'; protect=False: 'int' -> 'int'
Eric Blake18df5152015-05-14 06:50:48 -0600784def c_name(name, protect=True):
Blue Swirl427a1a22012-07-30 15:46:55 +0000785 # ANSI X3J11/88-090, 3.1.1
786 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
787 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
788 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
789 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
790 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
791 # ISO/IEC 9899:1999, 6.4.1
792 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
793 # ISO/IEC 9899:2011, 6.4.1
794 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
795 '_Static_assert', '_Thread_local'])
796 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
797 # excluding _.*
798 gcc_words = set(['asm', 'typeof'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400799 # C++ ISO/IEC 14882:2003 2.11
800 cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
801 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
802 'namespace', 'new', 'operator', 'private', 'protected',
803 'public', 'reinterpret_cast', 'static_cast', 'template',
804 'this', 'throw', 'true', 'try', 'typeid', 'typename',
805 'using', 'virtual', 'wchar_t',
806 # alternative representations
807 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
808 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
Paolo Bonzini10577252012-09-19 16:31:07 +0200809 # namespace pollution:
Max Reitz8592a542013-12-20 19:28:18 +0100810 polluted_words = set(['unix', 'errno'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400811 if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
Blue Swirl427a1a22012-07-30 15:46:55 +0000812 return "q_" + name
Eric Blake18df5152015-05-14 06:50:48 -0600813 return name.translate(c_name_trans)
Michael Roth0f923be2011-07-19 14:50:39 -0500814
Eric Blakec6405b52015-05-14 06:50:55 -0600815# Map type @name to the C typedef name for the list form.
816#
817# ['Name'] -> 'NameList', ['x-Foo'] -> 'x_FooList', ['int'] -> 'intList'
Michael Roth0f923be2011-07-19 14:50:39 -0500818def c_list_type(name):
Eric Blakec6405b52015-05-14 06:50:55 -0600819 return type_name(name) + 'List'
Michael Roth0f923be2011-07-19 14:50:39 -0500820
Eric Blakec6405b52015-05-14 06:50:55 -0600821# Map type @value to the C typedef form.
822#
823# Used for converting 'type' from a 'member':'type' qapi definition
824# into the alphanumeric portion of the type for a generated C parameter,
825# as well as generated C function names. See c_type() for the rest of
826# the conversion such as adding '*' on pointer types.
827# 'int' -> 'int', '[x-Foo]' -> 'x_FooList', '__a.b_c' -> '__a_b_c'
Eric Blaked5573442015-05-14 06:50:54 -0600828def type_name(value):
829 if type(value) == list:
830 return c_list_type(value[0])
Eric Blakec6405b52015-05-14 06:50:55 -0600831 if value in builtin_types.keys():
832 return value
833 return c_name(value)
Michael Roth0f923be2011-07-19 14:50:39 -0500834
Eric Blakefd41dd42015-05-04 09:05:25 -0600835def add_name(name, info, meta, implicit = False):
Eric Blake4dc2e692015-05-04 09:05:17 -0600836 global all_names
Eric Blakefd41dd42015-05-04 09:05:25 -0600837 check_name(info, "'%s'" % meta, name)
Eric Blake4dc2e692015-05-04 09:05:17 -0600838 if name in all_names:
839 raise QAPIExprError(info,
840 "%s '%s' is already defined"
841 % (all_names[name], name))
842 if not implicit and name[-4:] == 'Kind':
843 raise QAPIExprError(info,
844 "%s '%s' should not end in 'Kind'"
845 % (meta, name))
846 all_names[name] = meta
Kevin Wolfb35284e2013-07-01 16:31:51 +0200847
Eric Blake4dc2e692015-05-04 09:05:17 -0600848def add_struct(definition, info):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200849 global struct_types
Eric Blakefd41dd42015-05-04 09:05:25 -0600850 name = definition['struct']
851 add_name(name, info, 'struct')
Kevin Wolfb35284e2013-07-01 16:31:51 +0200852 struct_types.append(definition)
853
854def find_struct(name):
855 global struct_types
856 for struct in struct_types:
Eric Blakefd41dd42015-05-04 09:05:25 -0600857 if struct['struct'] == name:
Kevin Wolfb35284e2013-07-01 16:31:51 +0200858 return struct
859 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500860
Eric Blake4dc2e692015-05-04 09:05:17 -0600861def add_union(definition, info):
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200862 global union_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600863 name = definition['union']
864 add_name(name, info, 'union')
Eric Blakeab916fa2015-05-04 09:05:13 -0600865 union_types.append(definition)
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200866
867def find_union(name):
868 global union_types
869 for union in union_types:
870 if union['union'] == name:
871 return union
872 return None
873
Eric Blake4dc2e692015-05-04 09:05:17 -0600874def add_enum(name, info, enum_values = None, implicit = False):
Michael Roth0f923be2011-07-19 14:50:39 -0500875 global enum_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600876 add_name(name, info, 'enum', implicit)
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800877 enum_types.append({"enum_name": name, "enum_values": enum_values})
878
879def find_enum(name):
880 global enum_types
881 for enum in enum_types:
882 if enum['enum_name'] == name:
883 return enum
884 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500885
886def is_enum(name):
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800887 return find_enum(name) != None
Michael Roth0f923be2011-07-19 14:50:39 -0500888
Amos Kong05dfb262014-06-10 19:25:53 +0800889eatspace = '\033EATSPACE.'
Eric Blaked5573442015-05-14 06:50:54 -0600890pointer_suffix = ' *' + eatspace
Amos Kong05dfb262014-06-10 19:25:53 +0800891
Eric Blakec6405b52015-05-14 06:50:55 -0600892# Map type @name to its C type expression.
893# If @is_param, const-qualify the string type.
894#
895# This function is used for computing the full C type of 'member':'name'.
Amos Kong05dfb262014-06-10 19:25:53 +0800896# A special suffix is added in c_type() for pointer types, and it's
897# stripped in mcgen(). So please notice this when you check the return
898# value of c_type() outside mcgen().
Eric Blaked5573442015-05-14 06:50:54 -0600899def c_type(value, is_param=False):
900 if value == 'str':
Amos Kong0d14eeb2014-06-10 19:25:52 +0800901 if is_param:
Eric Blaked5573442015-05-14 06:50:54 -0600902 return 'const char' + pointer_suffix
903 return 'char' + pointer_suffix
Amos Kong05dfb262014-06-10 19:25:53 +0800904
Eric Blaked5573442015-05-14 06:50:54 -0600905 elif value == 'int':
Michael Roth0f923be2011-07-19 14:50:39 -0500906 return 'int64_t'
Eric Blaked5573442015-05-14 06:50:54 -0600907 elif (value == 'int8' or value == 'int16' or value == 'int32' or
908 value == 'int64' or value == 'uint8' or value == 'uint16' or
909 value == 'uint32' or value == 'uint64'):
910 return value + '_t'
911 elif value == 'size':
Laszlo Ersek092705d2012-07-17 16:17:07 +0200912 return 'uint64_t'
Eric Blaked5573442015-05-14 06:50:54 -0600913 elif value == 'bool':
Michael Roth0f923be2011-07-19 14:50:39 -0500914 return 'bool'
Eric Blaked5573442015-05-14 06:50:54 -0600915 elif value == 'number':
Michael Roth0f923be2011-07-19 14:50:39 -0500916 return 'double'
Eric Blaked5573442015-05-14 06:50:54 -0600917 elif type(value) == list:
918 return c_list_type(value[0]) + pointer_suffix
919 elif is_enum(value):
Eric Blakec6405b52015-05-14 06:50:55 -0600920 return c_name(value)
Eric Blaked5573442015-05-14 06:50:54 -0600921 elif value == None:
Michael Roth0f923be2011-07-19 14:50:39 -0500922 return 'void'
Eric Blaked5573442015-05-14 06:50:54 -0600923 elif value in events:
924 return camel_case(value) + 'Event' + pointer_suffix
Michael Roth0f923be2011-07-19 14:50:39 -0500925 else:
Eric Blaked5573442015-05-14 06:50:54 -0600926 # complex type name
927 assert isinstance(value, str) and value != ""
Eric Blakec6405b52015-05-14 06:50:55 -0600928 return c_name(value) + pointer_suffix
Amos Kong05dfb262014-06-10 19:25:53 +0800929
Eric Blaked5573442015-05-14 06:50:54 -0600930def is_c_ptr(value):
931 return c_type(value).endswith(pointer_suffix)
Michael Roth0f923be2011-07-19 14:50:39 -0500932
933def genindent(count):
934 ret = ""
935 for i in range(count):
936 ret += " "
937 return ret
938
939indent_level = 0
940
941def push_indent(indent_amount=4):
942 global indent_level
943 indent_level += indent_amount
944
945def pop_indent(indent_amount=4):
946 global indent_level
947 indent_level -= indent_amount
948
949def cgen(code, **kwds):
950 indent = genindent(indent_level)
951 lines = code.split('\n')
952 lines = map(lambda x: indent + x, lines)
953 return '\n'.join(lines) % kwds + '\n'
954
955def mcgen(code, **kwds):
Amos Kong05dfb262014-06-10 19:25:53 +0800956 raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
957 return re.sub(re.escape(eatspace) + ' *', '', raw)
Michael Roth0f923be2011-07-19 14:50:39 -0500958
959def basename(filename):
960 return filename.split("/")[-1]
961
962def guardname(filename):
Michael Rothd8e1f212011-11-29 16:47:48 -0600963 guard = basename(filename).rsplit(".", 1)[0]
964 for substr in [".", " ", "-"]:
965 guard = guard.replace(substr, "_")
966 return guard.upper() + '_H'
Michael Rothc0afa9c2013-05-10 17:46:00 -0500967
968def guardstart(name):
969 return mcgen('''
970
971#ifndef %(name)s
972#define %(name)s
973
974''',
975 name=guardname(name))
976
977def guardend(name):
978 return mcgen('''
979
980#endif /* %(name)s */
981
982''',
983 name=guardname(name))
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200984
985def parse_command_line(extra_options = "", extra_long_options = []):
986
987 try:
988 opts, args = getopt.gnu_getopt(sys.argv[1:],
Markus Armbruster16d80f62015-04-02 13:32:16 +0200989 "chp:o:" + extra_options,
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200990 ["source", "header", "prefix=",
Markus Armbruster16d80f62015-04-02 13:32:16 +0200991 "output-dir="] + extra_long_options)
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200992 except getopt.GetoptError, err:
Markus Armbrusterb4540962015-04-02 13:17:34 +0200993 print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200994 sys.exit(1)
995
996 output_dir = ""
997 prefix = ""
998 do_c = False
999 do_h = False
1000 extra_opts = []
1001
1002 for oa in opts:
1003 o, a = oa
1004 if o in ("-p", "--prefix"):
1005 prefix = a
Markus Armbruster2114f5a2015-04-02 13:12:21 +02001006 elif o in ("-o", "--output-dir"):
1007 output_dir = a + "/"
1008 elif o in ("-c", "--source"):
1009 do_c = True
1010 elif o in ("-h", "--header"):
1011 do_h = True
1012 else:
1013 extra_opts.append(oa)
1014
1015 if not do_c and not do_h:
1016 do_c = True
1017 do_h = True
1018
Markus Armbruster16d80f62015-04-02 13:32:16 +02001019 if len(args) != 1:
1020 print >>sys.stderr, "%s: need exactly one argument" % sys.argv[0]
Markus Armbrusterb4540962015-04-02 13:17:34 +02001021 sys.exit(1)
Markus Armbruster54414042015-06-09 16:22:45 +02001022 fname = args[0]
Markus Armbrusterb4540962015-04-02 13:17:34 +02001023
Markus Armbruster54414042015-06-09 16:22:45 +02001024 return (fname, output_dir, do_c, do_h, prefix, extra_opts)
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001025
1026def open_output(output_dir, do_c, do_h, prefix, c_file, h_file,
1027 c_comment, h_comment):
1028 c_file = output_dir + prefix + c_file
1029 h_file = output_dir + prefix + h_file
1030
1031 try:
1032 os.makedirs(output_dir)
1033 except os.error, e:
1034 if e.errno != errno.EEXIST:
1035 raise
1036
1037 def maybe_open(really, name, opt):
1038 if really:
1039 return open(name, opt)
1040 else:
1041 import StringIO
1042 return StringIO.StringIO()
1043
1044 fdef = maybe_open(do_c, c_file, 'w')
1045 fdecl = maybe_open(do_h, h_file, 'w')
1046
1047 fdef.write(mcgen('''
1048/* AUTOMATICALLY GENERATED, DO NOT MODIFY */
1049%(comment)s
1050''',
1051 comment = c_comment))
1052
1053 fdecl.write(mcgen('''
1054/* AUTOMATICALLY GENERATED, DO NOT MODIFY */
1055%(comment)s
1056#ifndef %(guard)s
1057#define %(guard)s
1058
1059''',
1060 comment = h_comment, guard = guardname(h_file)))
1061
1062 return (fdef, fdecl)
1063
1064def close_output(fdef, fdecl):
1065 fdecl.write('''
1066#endif
1067''')
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001068 fdecl.close()
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001069 fdef.close()