blob: 34a5e8de95c052056f0d65ba4967af9260682b2c [file] [log] [blame]
Michael Roth0f923be2011-07-19 14:50:39 -05001#
2# QAPI helper library
3#
4# Copyright IBM, Corp. 2011
Eric Blakefe2a9302015-05-04 09:05:02 -06005# Copyright (c) 2013-2015 Red Hat Inc.
Michael Roth0f923be2011-07-19 14:50:39 -05006#
7# Authors:
8# Anthony Liguori <aliguori@us.ibm.com>
Markus Armbrusterc7a3f252013-07-27 17:41:55 +02009# Markus Armbruster <armbru@redhat.com>
Michael Roth0f923be2011-07-19 14:50:39 -050010#
Markus Armbruster678e48a2014-03-01 08:40:34 +010011# This work is licensed under the terms of the GNU GPL, version 2.
12# See the COPYING file in the top-level directory.
Michael Roth0f923be2011-07-19 14:50:39 -050013
Lluís Vilanovaa719a272014-05-07 20:46:15 +020014import re
Michael Roth0f923be2011-07-19 14:50:39 -050015from ordereddict import OrderedDict
Markus Armbruster12f8e1b2015-04-02 14:46:39 +020016import errno
Markus Armbruster2114f5a2015-04-02 13:12:21 +020017import getopt
Lluís Vilanova33aaad52014-05-02 15:52:35 +020018import os
Markus Armbruster2caba362013-07-27 17:41:56 +020019import sys
Markus Armbruster47299262015-05-14 06:50:47 -060020import string
Michael Roth0f923be2011-07-19 14:50:39 -050021
Eric Blakeb52c4b92015-05-04 09:05:00 -060022builtin_types = {
Kevin Wolf69dd62d2013-07-08 16:14:21 +020023 'str': 'QTYPE_QSTRING',
24 'int': 'QTYPE_QINT',
25 'number': 'QTYPE_QFLOAT',
26 'bool': 'QTYPE_QBOOL',
27 'int8': 'QTYPE_QINT',
28 'int16': 'QTYPE_QINT',
29 'int32': 'QTYPE_QINT',
30 'int64': 'QTYPE_QINT',
31 'uint8': 'QTYPE_QINT',
32 'uint16': 'QTYPE_QINT',
33 'uint32': 'QTYPE_QINT',
34 'uint64': 'QTYPE_QINT',
Eric Blakecb17f792015-05-04 09:05:01 -060035 'size': 'QTYPE_QINT',
Kevin Wolf69dd62d2013-07-08 16:14:21 +020036}
37
Eric Blake10d4d992015-05-04 09:05:23 -060038# Whitelist of commands allowed to return a non-dictionary
39returns_whitelist = [
40 # From QMP:
41 'human-monitor-command',
42 'query-migrate-cache-size',
43 'query-tpm-models',
44 'query-tpm-types',
45 'ringbuf-read',
46
47 # From QGA:
48 'guest-file-open',
49 'guest-fsfreeze-freeze',
50 'guest-fsfreeze-freeze-list',
51 'guest-fsfreeze-status',
52 'guest-fsfreeze-thaw',
53 'guest-get-time',
54 'guest-set-vcpus',
55 'guest-sync',
56 'guest-sync-delimited',
57
58 # From qapi-schema-test:
59 'user_def_cmd3',
60]
61
Eric Blake4dc2e692015-05-04 09:05:17 -060062enum_types = []
63struct_types = []
64union_types = []
65events = []
66all_names = {}
67
Lluís Vilanovaa719a272014-05-07 20:46:15 +020068def error_path(parent):
69 res = ""
70 while parent:
71 res = ("In file included from %s:%d:\n" % (parent['file'],
72 parent['line'])) + res
73 parent = parent['parent']
74 return res
75
Markus Armbruster2caba362013-07-27 17:41:56 +020076class QAPISchemaError(Exception):
77 def __init__(self, schema, msg):
Markus Armbruster54414042015-06-09 16:22:45 +020078 self.fname = schema.fname
Markus Armbruster2caba362013-07-27 17:41:56 +020079 self.msg = msg
Wenchao Xia515b9432014-03-04 18:44:33 -080080 self.col = 1
81 self.line = schema.line
82 for ch in schema.src[schema.line_pos:schema.pos]:
83 if ch == '\t':
Markus Armbruster2caba362013-07-27 17:41:56 +020084 self.col = (self.col + 7) % 8 + 1
85 else:
86 self.col += 1
Markus Armbruster54414042015-06-09 16:22:45 +020087 self.info = schema.incl_info
Markus Armbruster2caba362013-07-27 17:41:56 +020088
89 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020090 return error_path(self.info) + \
Markus Armbruster54414042015-06-09 16:22:45 +020091 "%s:%d:%d: %s" % (self.fname, self.line, self.col, self.msg)
Markus Armbruster2caba362013-07-27 17:41:56 +020092
Wenchao Xiab86b05e2014-03-04 18:44:34 -080093class QAPIExprError(Exception):
94 def __init__(self, expr_info, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020095 self.info = expr_info
Wenchao Xiab86b05e2014-03-04 18:44:34 -080096 self.msg = msg
97
98 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020099 return error_path(self.info['parent']) + \
100 "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800101
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200102class QAPISchema:
Michael Roth0f923be2011-07-19 14:50:39 -0500103
Markus Armbrustera1366082015-06-09 16:54:09 +0200104 def __init__(self, fp, previously_included = [], incl_info = None):
Markus Armbruster54414042015-06-09 16:22:45 +0200105 abs_fname = os.path.abspath(fp.name)
Markus Armbruster8608d252015-06-09 18:32:29 +0200106 fname = fp.name
Markus Armbruster54414042015-06-09 16:22:45 +0200107 self.fname = fname
Markus Armbruster54414042015-06-09 16:22:45 +0200108 previously_included.append(abs_fname)
109 self.incl_info = incl_info
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200110 self.src = fp.read()
111 if self.src == '' or self.src[-1] != '\n':
112 self.src += '\n'
113 self.cursor = 0
Wenchao Xia515b9432014-03-04 18:44:33 -0800114 self.line = 1
115 self.line_pos = 0
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200116 self.exprs = []
117 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500118
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200119 while self.tok != None:
Markus Armbruster54414042015-06-09 16:22:45 +0200120 expr_info = {'file': fname, 'line': self.line,
121 'parent': self.incl_info}
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200122 expr = self.get_expr(False)
123 if isinstance(expr, dict) and "include" in expr:
124 if len(expr) != 1:
125 raise QAPIExprError(expr_info, "Invalid 'include' directive")
126 include = expr["include"]
127 if not isinstance(include, str):
128 raise QAPIExprError(expr_info,
129 'Expected a file name (string), got: %s'
130 % include)
Markus Armbruster54414042015-06-09 16:22:45 +0200131 incl_abs_fname = os.path.join(os.path.dirname(abs_fname),
132 include)
Markus Armbrustera1366082015-06-09 16:54:09 +0200133 # catch inclusion cycle
134 inf = expr_info
135 while inf:
136 if incl_abs_fname == os.path.abspath(inf['file']):
Stefan Hajnoczi7ac9a9d2014-08-27 12:08:51 +0100137 raise QAPIExprError(expr_info, "Inclusion loop for %s"
138 % include)
Markus Armbrustera1366082015-06-09 16:54:09 +0200139 inf = inf['parent']
Benoît Canet24fd8482014-05-16 12:51:56 +0200140 # skip multiple include of the same file
Markus Armbruster54414042015-06-09 16:22:45 +0200141 if incl_abs_fname in previously_included:
Benoît Canet24fd8482014-05-16 12:51:56 +0200142 continue
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200143 try:
Markus Armbruster54414042015-06-09 16:22:45 +0200144 fobj = open(incl_abs_fname, 'r')
Luiz Capitulino34788812014-05-20 13:50:19 -0400145 except IOError, e:
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200146 raise QAPIExprError(expr_info,
147 '%s: %s' % (e.strerror, include))
Markus Armbrustera1366082015-06-09 16:54:09 +0200148 exprs_include = QAPISchema(fobj, previously_included,
149 expr_info)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200150 self.exprs.extend(exprs_include.exprs)
151 else:
152 expr_elem = {'expr': expr,
153 'info': expr_info}
154 self.exprs.append(expr_elem)
Michael Roth0f923be2011-07-19 14:50:39 -0500155
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200156 def accept(self):
157 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200158 self.tok = self.src[self.cursor]
Markus Armbruster2caba362013-07-27 17:41:56 +0200159 self.pos = self.cursor
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200160 self.cursor += 1
161 self.val = None
Michael Roth0f923be2011-07-19 14:50:39 -0500162
Markus Armbrusterf1a145e2013-07-27 17:42:01 +0200163 if self.tok == '#':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200164 self.cursor = self.src.find('\n', self.cursor)
165 elif self.tok in ['{', '}', ':', ',', '[', ']']:
166 return
167 elif self.tok == "'":
168 string = ''
169 esc = False
170 while True:
171 ch = self.src[self.cursor]
172 self.cursor += 1
173 if ch == '\n':
Markus Armbruster2caba362013-07-27 17:41:56 +0200174 raise QAPISchemaError(self,
175 'Missing terminating "\'"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200176 if esc:
Eric Blakea7f59662015-05-04 09:05:36 -0600177 if ch == 'b':
178 string += '\b'
179 elif ch == 'f':
180 string += '\f'
181 elif ch == 'n':
182 string += '\n'
183 elif ch == 'r':
184 string += '\r'
185 elif ch == 't':
186 string += '\t'
187 elif ch == 'u':
188 value = 0
189 for x in range(0, 4):
190 ch = self.src[self.cursor]
191 self.cursor += 1
192 if ch not in "0123456789abcdefABCDEF":
193 raise QAPISchemaError(self,
194 '\\u escape needs 4 '
195 'hex digits')
196 value = (value << 4) + int(ch, 16)
197 # If Python 2 and 3 didn't disagree so much on
198 # how to handle Unicode, then we could allow
199 # Unicode string defaults. But most of QAPI is
200 # ASCII-only, so we aren't losing much for now.
201 if not value or value > 0x7f:
202 raise QAPISchemaError(self,
203 'For now, \\u escape '
204 'only supports non-zero '
205 'values up to \\u007f')
206 string += chr(value)
207 elif ch in "\\/'\"":
208 string += ch
209 else:
210 raise QAPISchemaError(self,
211 "Unknown escape \\%s" %ch)
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200212 esc = False
213 elif ch == "\\":
214 esc = True
215 elif ch == "'":
216 self.val = string
217 return
218 else:
219 string += ch
Markus Armbrustere565d932015-06-10 08:24:58 +0200220 elif self.src.startswith("true", self.pos):
221 self.val = True
222 self.cursor += 3
223 return
224 elif self.src.startswith("false", self.pos):
225 self.val = False
226 self.cursor += 4
227 return
228 elif self.src.startswith("null", self.pos):
229 self.val = None
230 self.cursor += 3
231 return
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200232 elif self.tok == '\n':
233 if self.cursor == len(self.src):
234 self.tok = None
235 return
Wenchao Xia515b9432014-03-04 18:44:33 -0800236 self.line += 1
237 self.line_pos = self.cursor
Markus Armbruster9213aa52013-07-27 17:41:57 +0200238 elif not self.tok.isspace():
239 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
Michael Roth0f923be2011-07-19 14:50:39 -0500240
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200241 def get_members(self):
242 expr = OrderedDict()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200243 if self.tok == '}':
244 self.accept()
245 return expr
246 if self.tok != "'":
247 raise QAPISchemaError(self, 'Expected string or "}"')
248 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200249 key = self.val
250 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200251 if self.tok != ':':
252 raise QAPISchemaError(self, 'Expected ":"')
253 self.accept()
Wenchao Xia4b359912014-03-04 18:44:32 -0800254 if key in expr:
255 raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200256 expr[key] = self.get_expr(True)
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200257 if self.tok == '}':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200258 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200259 return expr
260 if self.tok != ',':
261 raise QAPISchemaError(self, 'Expected "," or "}"')
262 self.accept()
263 if self.tok != "'":
264 raise QAPISchemaError(self, 'Expected string')
Michael Roth0f923be2011-07-19 14:50:39 -0500265
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200266 def get_values(self):
267 expr = []
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200268 if self.tok == ']':
269 self.accept()
270 return expr
Fam Zhenge53188a2015-05-04 09:05:18 -0600271 if not self.tok in "{['tfn":
272 raise QAPISchemaError(self, 'Expected "{", "[", "]", string, '
273 'boolean or "null"')
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200274 while True:
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200275 expr.append(self.get_expr(True))
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200276 if self.tok == ']':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200277 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200278 return expr
279 if self.tok != ',':
280 raise QAPISchemaError(self, 'Expected "," or "]"')
281 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500282
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200283 def get_expr(self, nested):
284 if self.tok != '{' and not nested:
285 raise QAPISchemaError(self, 'Expected "{"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200286 if self.tok == '{':
287 self.accept()
288 expr = self.get_members()
289 elif self.tok == '[':
290 self.accept()
291 expr = self.get_values()
Fam Zhenge53188a2015-05-04 09:05:18 -0600292 elif self.tok in "'tfn":
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200293 expr = self.val
294 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200295 else:
296 raise QAPISchemaError(self, 'Expected "{", "[" or string')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200297 return expr
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200298
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800299def find_base_fields(base):
300 base_struct_define = find_struct(base)
301 if not base_struct_define:
302 return None
303 return base_struct_define['data']
304
Eric Blake811d04f2015-05-04 09:05:10 -0600305# Return the qtype of an alternate branch, or None on error.
306def find_alternate_member_qtype(qapi_type):
Eric Blake44bd1272015-05-04 09:05:08 -0600307 if builtin_types.has_key(qapi_type):
308 return builtin_types[qapi_type]
309 elif find_struct(qapi_type):
310 return "QTYPE_QDICT"
311 elif find_enum(qapi_type):
312 return "QTYPE_QSTRING"
Eric Blake811d04f2015-05-04 09:05:10 -0600313 elif find_union(qapi_type):
314 return "QTYPE_QDICT"
Eric Blake44bd1272015-05-04 09:05:08 -0600315 return None
316
Wenchao Xiabceae762014-03-06 17:08:56 -0800317# Return the discriminator enum define if discriminator is specified as an
318# enum type, otherwise return None.
319def discriminator_find_enum_define(expr):
320 base = expr.get('base')
321 discriminator = expr.get('discriminator')
322
323 if not (discriminator and base):
324 return None
325
326 base_fields = find_base_fields(base)
327 if not base_fields:
328 return None
329
330 discriminator_type = base_fields.get(discriminator)
331 if not discriminator_type:
332 return None
333
334 return find_enum(discriminator_type)
335
Eric Blakec9e0a792015-05-04 09:05:22 -0600336valid_name = re.compile('^[a-zA-Z_][a-zA-Z0-9_.-]*$')
337def check_name(expr_info, source, name, allow_optional = False,
338 enum_member = False):
339 global valid_name
340 membername = name
341
342 if not isinstance(name, str):
343 raise QAPIExprError(expr_info,
344 "%s requires a string name" % source)
345 if name.startswith('*'):
346 membername = name[1:]
347 if not allow_optional:
348 raise QAPIExprError(expr_info,
349 "%s does not allow optional name '%s'"
350 % (source, name))
351 # Enum members can start with a digit, because the generated C
352 # code always prefixes it with the enum name
353 if enum_member:
354 membername = '_' + membername
355 if not valid_name.match(membername):
356 raise QAPIExprError(expr_info,
357 "%s uses invalid name '%s'" % (source, name))
358
Eric Blakedd883c62015-05-04 09:05:21 -0600359def check_type(expr_info, source, value, allow_array = False,
Eric Blake2cbf0992015-05-04 09:05:24 -0600360 allow_dict = False, allow_optional = False,
361 allow_star = False, allow_metas = []):
Eric Blakedd883c62015-05-04 09:05:21 -0600362 global all_names
363 orig_value = value
364
365 if value is None:
366 return
367
Eric Blake2cbf0992015-05-04 09:05:24 -0600368 if allow_star and value == '**':
Eric Blakedd883c62015-05-04 09:05:21 -0600369 return
370
371 # Check if array type for value is okay
372 if isinstance(value, list):
373 if not allow_array:
374 raise QAPIExprError(expr_info,
375 "%s cannot be an array" % source)
376 if len(value) != 1 or not isinstance(value[0], str):
377 raise QAPIExprError(expr_info,
378 "%s: array type must contain single type name"
379 % source)
380 value = value[0]
381 orig_value = "array of %s" %value
382
383 # Check if type name for value is okay
384 if isinstance(value, str):
Eric Blake2cbf0992015-05-04 09:05:24 -0600385 if value == '**':
386 raise QAPIExprError(expr_info,
387 "%s uses '**' but did not request 'gen':false"
388 % source)
Eric Blakedd883c62015-05-04 09:05:21 -0600389 if not value in all_names:
390 raise QAPIExprError(expr_info,
391 "%s uses unknown type '%s'"
392 % (source, orig_value))
393 if not all_names[value] in allow_metas:
394 raise QAPIExprError(expr_info,
395 "%s cannot use %s type '%s'"
396 % (source, all_names[value], orig_value))
397 return
398
399 # value is a dictionary, check that each member is okay
400 if not isinstance(value, OrderedDict):
401 raise QAPIExprError(expr_info,
402 "%s should be a dictionary" % source)
403 if not allow_dict:
404 raise QAPIExprError(expr_info,
405 "%s should be a type name" % source)
406 for (key, arg) in value.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600407 check_name(expr_info, "Member of %s" % source, key,
408 allow_optional=allow_optional)
Eric Blake6b5abc72015-05-04 09:05:33 -0600409 # Todo: allow dictionaries to represent default values of
410 # an optional argument.
Eric Blakedd883c62015-05-04 09:05:21 -0600411 check_type(expr_info, "Member '%s' of %s" % (key, source), arg,
Eric Blake6b5abc72015-05-04 09:05:33 -0600412 allow_array=True, allow_star=allow_star,
Eric Blakedd883c62015-05-04 09:05:21 -0600413 allow_metas=['built-in', 'union', 'alternate', 'struct',
Eric Blake6b5abc72015-05-04 09:05:33 -0600414 'enum'])
Eric Blakedd883c62015-05-04 09:05:21 -0600415
Eric Blakeff55d722015-05-04 09:05:37 -0600416def check_member_clash(expr_info, base_name, data, source = ""):
417 base = find_struct(base_name)
418 assert base
419 base_members = base['data']
420 for key in data.keys():
421 if key.startswith('*'):
422 key = key[1:]
423 if key in base_members or "*" + key in base_members:
424 raise QAPIExprError(expr_info,
425 "Member name '%s'%s clashes with base '%s'"
426 % (key, source, base_name))
427 if base.get('base'):
428 check_member_clash(expr_info, base['base'], data, source)
429
Eric Blakedd883c62015-05-04 09:05:21 -0600430def check_command(expr, expr_info):
431 name = expr['command']
Eric Blake2cbf0992015-05-04 09:05:24 -0600432 allow_star = expr.has_key('gen')
433
Eric Blakedd883c62015-05-04 09:05:21 -0600434 check_type(expr_info, "'data' for command '%s'" % name,
Eric Blakec9e0a792015-05-04 09:05:22 -0600435 expr.get('data'), allow_dict=True, allow_optional=True,
Eric Blake2cbf0992015-05-04 09:05:24 -0600436 allow_metas=['union', 'struct'], allow_star=allow_star)
Eric Blake10d4d992015-05-04 09:05:23 -0600437 returns_meta = ['union', 'struct']
438 if name in returns_whitelist:
439 returns_meta += ['built-in', 'alternate', 'enum']
Eric Blakedd883c62015-05-04 09:05:21 -0600440 check_type(expr_info, "'returns' for command '%s'" % name,
441 expr.get('returns'), allow_array=True, allow_dict=True,
Eric Blake2cbf0992015-05-04 09:05:24 -0600442 allow_optional=True, allow_metas=returns_meta,
443 allow_star=allow_star)
Eric Blakedd883c62015-05-04 09:05:21 -0600444
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200445def check_event(expr, expr_info):
Eric Blake4dc2e692015-05-04 09:05:17 -0600446 global events
447 name = expr['event']
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200448 params = expr.get('data')
Eric Blake4dc2e692015-05-04 09:05:17 -0600449
450 if name.upper() == 'MAX':
451 raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created")
452 events.append(name)
Eric Blakedd883c62015-05-04 09:05:21 -0600453 check_type(expr_info, "'data' for event '%s'" % name,
Eric Blakec9e0a792015-05-04 09:05:22 -0600454 expr.get('data'), allow_dict=True, allow_optional=True,
Eric Blakedd883c62015-05-04 09:05:21 -0600455 allow_metas=['union', 'struct'])
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200456
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800457def check_union(expr, expr_info):
458 name = expr['union']
459 base = expr.get('base')
460 discriminator = expr.get('discriminator')
461 members = expr['data']
Eric Blake44bd1272015-05-04 09:05:08 -0600462 values = { 'MAX': '(automatic)' }
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800463
Eric Blakefd41dd42015-05-04 09:05:25 -0600464 # If the object has a member 'base', its value must name a struct,
Eric Blakea8d4a2e2015-05-04 09:05:07 -0600465 # and there must be a discriminator.
466 if base is not None:
467 if discriminator is None:
468 raise QAPIExprError(expr_info,
469 "Union '%s' requires a discriminator to go "
470 "along with base" %name)
Eric Blake44bd1272015-05-04 09:05:08 -0600471
Eric Blake811d04f2015-05-04 09:05:10 -0600472 # Two types of unions, determined by discriminator.
Eric Blake811d04f2015-05-04 09:05:10 -0600473
474 # With no discriminator it is a simple union.
475 if discriminator is None:
Eric Blake44bd1272015-05-04 09:05:08 -0600476 enum_define = None
Eric Blakedd883c62015-05-04 09:05:21 -0600477 allow_metas=['built-in', 'union', 'alternate', 'struct', 'enum']
Eric Blake44bd1272015-05-04 09:05:08 -0600478 if base is not None:
479 raise QAPIExprError(expr_info,
Eric Blake811d04f2015-05-04 09:05:10 -0600480 "Simple union '%s' must not have a base"
Eric Blake44bd1272015-05-04 09:05:08 -0600481 % name)
482
483 # Else, it's a flat union.
484 else:
485 # The object must have a string member 'base'.
486 if not isinstance(base, str):
487 raise QAPIExprError(expr_info,
488 "Flat union '%s' must have a string base field"
489 % name)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800490 base_fields = find_base_fields(base)
491 if not base_fields:
492 raise QAPIExprError(expr_info,
Eric Blakefd41dd42015-05-04 09:05:25 -0600493 "Base '%s' is not a valid struct"
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800494 % base)
495
Eric Blakec9e0a792015-05-04 09:05:22 -0600496 # The value of member 'discriminator' must name a non-optional
Eric Blakefd41dd42015-05-04 09:05:25 -0600497 # member of the base struct.
Eric Blakec9e0a792015-05-04 09:05:22 -0600498 check_name(expr_info, "Discriminator of flat union '%s'" % name,
499 discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800500 discriminator_type = base_fields.get(discriminator)
501 if not discriminator_type:
502 raise QAPIExprError(expr_info,
503 "Discriminator '%s' is not a member of base "
Eric Blakefd41dd42015-05-04 09:05:25 -0600504 "struct '%s'"
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800505 % (discriminator, base))
506 enum_define = find_enum(discriminator_type)
Eric Blakedd883c62015-05-04 09:05:21 -0600507 allow_metas=['struct']
Wenchao Xia52230702014-03-04 18:44:39 -0800508 # Do not allow string discriminator
509 if not enum_define:
510 raise QAPIExprError(expr_info,
511 "Discriminator '%s' must be of enumeration "
512 "type" % discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800513
514 # Check every branch
515 for (key, value) in members.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600516 check_name(expr_info, "Member of union '%s'" % name, key)
517
Eric Blakedd883c62015-05-04 09:05:21 -0600518 # Each value must name a known type; furthermore, in flat unions,
Eric Blakeff55d722015-05-04 09:05:37 -0600519 # branches must be a struct with no overlapping member names
Eric Blakedd883c62015-05-04 09:05:21 -0600520 check_type(expr_info, "Member '%s' of union '%s'" % (key, name),
521 value, allow_array=True, allow_metas=allow_metas)
Eric Blakeff55d722015-05-04 09:05:37 -0600522 if base:
523 branch_struct = find_struct(value)
524 assert branch_struct
525 check_member_clash(expr_info, base, branch_struct['data'],
526 " of branch '%s'" % key)
Eric Blakedd883c62015-05-04 09:05:21 -0600527
Eric Blake44bd1272015-05-04 09:05:08 -0600528 # If the discriminator names an enum type, then all members
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800529 # of 'data' must also be members of the enum type.
Eric Blake44bd1272015-05-04 09:05:08 -0600530 if enum_define:
531 if not key in enum_define['enum_values']:
532 raise QAPIExprError(expr_info,
533 "Discriminator value '%s' is not found in "
534 "enum '%s'" %
535 (key, enum_define["enum_name"]))
536
537 # Otherwise, check for conflicts in the generated enum
538 else:
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600539 c_key = camel_to_upper(key)
Eric Blake44bd1272015-05-04 09:05:08 -0600540 if c_key in values:
541 raise QAPIExprError(expr_info,
542 "Union '%s' member '%s' clashes with '%s'"
543 % (name, key, values[c_key]))
544 values[c_key] = key
545
Eric Blake811d04f2015-05-04 09:05:10 -0600546def check_alternate(expr, expr_info):
Eric Blakeab916fa2015-05-04 09:05:13 -0600547 name = expr['alternate']
Eric Blake811d04f2015-05-04 09:05:10 -0600548 members = expr['data']
549 values = { 'MAX': '(automatic)' }
550 types_seen = {}
Eric Blake44bd1272015-05-04 09:05:08 -0600551
Eric Blake811d04f2015-05-04 09:05:10 -0600552 # Check every branch
553 for (key, value) in members.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600554 check_name(expr_info, "Member of alternate '%s'" % name, key)
555
Eric Blake811d04f2015-05-04 09:05:10 -0600556 # Check for conflicts in the generated enum
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600557 c_key = camel_to_upper(key)
Eric Blake811d04f2015-05-04 09:05:10 -0600558 if c_key in values:
559 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600560 "Alternate '%s' member '%s' clashes with '%s'"
561 % (name, key, values[c_key]))
Eric Blake811d04f2015-05-04 09:05:10 -0600562 values[c_key] = key
563
564 # Ensure alternates have no type conflicts.
Eric Blakedd883c62015-05-04 09:05:21 -0600565 check_type(expr_info, "Member '%s' of alternate '%s'" % (key, name),
566 value,
567 allow_metas=['built-in', 'union', 'struct', 'enum'])
Eric Blake811d04f2015-05-04 09:05:10 -0600568 qtype = find_alternate_member_qtype(value)
Eric Blakedd883c62015-05-04 09:05:21 -0600569 assert qtype
Eric Blake811d04f2015-05-04 09:05:10 -0600570 if qtype in types_seen:
571 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600572 "Alternate '%s' member '%s' can't "
Eric Blake811d04f2015-05-04 09:05:10 -0600573 "be distinguished from member '%s'"
574 % (name, key, types_seen[qtype]))
575 types_seen[qtype] = key
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800576
Eric Blakecf393592015-05-04 09:05:04 -0600577def check_enum(expr, expr_info):
578 name = expr['enum']
579 members = expr.get('data')
580 values = { 'MAX': '(automatic)' }
581
582 if not isinstance(members, list):
583 raise QAPIExprError(expr_info,
584 "Enum '%s' requires an array for 'data'" % name)
585 for member in members:
Eric Blakec9e0a792015-05-04 09:05:22 -0600586 check_name(expr_info, "Member of enum '%s'" %name, member,
587 enum_member=True)
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600588 key = camel_to_upper(member)
Eric Blakecf393592015-05-04 09:05:04 -0600589 if key in values:
590 raise QAPIExprError(expr_info,
591 "Enum '%s' member '%s' clashes with '%s'"
592 % (name, member, values[key]))
593 values[key] = member
594
Eric Blakedd883c62015-05-04 09:05:21 -0600595def check_struct(expr, expr_info):
Eric Blakefd41dd42015-05-04 09:05:25 -0600596 name = expr['struct']
Eric Blakedd883c62015-05-04 09:05:21 -0600597 members = expr['data']
598
Eric Blakefd41dd42015-05-04 09:05:25 -0600599 check_type(expr_info, "'data' for struct '%s'" % name, members,
Eric Blakec9e0a792015-05-04 09:05:22 -0600600 allow_dict=True, allow_optional=True)
Eric Blakefd41dd42015-05-04 09:05:25 -0600601 check_type(expr_info, "'base' for struct '%s'" % name, expr.get('base'),
Eric Blakedd883c62015-05-04 09:05:21 -0600602 allow_metas=['struct'])
Eric Blakeff55d722015-05-04 09:05:37 -0600603 if expr.get('base'):
604 check_member_clash(expr_info, expr['base'], expr['data'])
Eric Blakedd883c62015-05-04 09:05:21 -0600605
Eric Blake0545f6b2015-05-04 09:05:15 -0600606def check_keys(expr_elem, meta, required, optional=[]):
607 expr = expr_elem['expr']
608 info = expr_elem['info']
609 name = expr[meta]
610 if not isinstance(name, str):
611 raise QAPIExprError(info,
612 "'%s' key must have a string value" % meta)
613 required = required + [ meta ]
614 for (key, value) in expr.items():
615 if not key in required and not key in optional:
616 raise QAPIExprError(info,
617 "Unknown key '%s' in %s '%s'"
618 % (key, meta, name))
Eric Blake2cbf0992015-05-04 09:05:24 -0600619 if (key == 'gen' or key == 'success-response') and value != False:
620 raise QAPIExprError(info,
621 "'%s' of %s '%s' should only use false value"
622 % (key, meta, name))
Eric Blake0545f6b2015-05-04 09:05:15 -0600623 for key in required:
624 if not expr.has_key(key):
625 raise QAPIExprError(info,
626 "Key '%s' is missing from %s '%s'"
627 % (key, meta, name))
628
Markus Armbruster4d076d62015-06-10 08:55:21 +0200629def check_exprs(exprs):
630 global all_names
631
632 # Learn the types and check for valid expression keys
633 for builtin in builtin_types.keys():
634 all_names[builtin] = 'built-in'
635 for expr_elem in exprs:
636 expr = expr_elem['expr']
637 info = expr_elem['info']
638 if expr.has_key('enum'):
639 check_keys(expr_elem, 'enum', ['data'])
640 add_enum(expr['enum'], info, expr['data'])
641 elif expr.has_key('union'):
642 check_keys(expr_elem, 'union', ['data'],
643 ['base', 'discriminator'])
644 add_union(expr, info)
645 elif expr.has_key('alternate'):
646 check_keys(expr_elem, 'alternate', ['data'])
647 add_name(expr['alternate'], info, 'alternate')
648 elif expr.has_key('struct'):
649 check_keys(expr_elem, 'struct', ['data'], ['base'])
650 add_struct(expr, info)
651 elif expr.has_key('command'):
652 check_keys(expr_elem, 'command', [],
653 ['data', 'returns', 'gen', 'success-response'])
654 add_name(expr['command'], info, 'command')
655 elif expr.has_key('event'):
656 check_keys(expr_elem, 'event', [], ['data'])
657 add_name(expr['event'], info, 'event')
658 else:
659 raise QAPIExprError(expr_elem['info'],
660 "Expression is missing metatype")
661
662 # Try again for hidden UnionKind enum
663 for expr_elem in exprs:
664 expr = expr_elem['expr']
665 if expr.has_key('union'):
666 if not discriminator_find_enum_define(expr):
667 add_enum('%sKind' % expr['union'], expr_elem['info'],
668 implicit=True)
669 elif expr.has_key('alternate'):
670 add_enum('%sKind' % expr['alternate'], expr_elem['info'],
671 implicit=True)
672
673 # Validate that exprs make sense
674 for expr_elem in exprs:
675 expr = expr_elem['expr']
676 info = expr_elem['info']
677
678 if expr.has_key('enum'):
679 check_enum(expr, info)
680 elif expr.has_key('union'):
681 check_union(expr, info)
682 elif expr.has_key('alternate'):
683 check_alternate(expr, info)
684 elif expr.has_key('struct'):
685 check_struct(expr, info)
686 elif expr.has_key('command'):
687 check_command(expr, info)
688 elif expr.has_key('event'):
689 check_event(expr, info)
690 else:
691 assert False, 'unexpected meta type'
692
693 return map(lambda expr_elem: expr_elem['expr'], exprs)
Eric Blake0545f6b2015-05-04 09:05:15 -0600694
Markus Armbruster54414042015-06-09 16:22:45 +0200695def parse_schema(fname):
Markus Armbruster2caba362013-07-27 17:41:56 +0200696 try:
Markus Armbruster54414042015-06-09 16:22:45 +0200697 schema = QAPISchema(open(fname, "r"))
Markus Armbruster4d076d62015-06-10 08:55:21 +0200698 return check_exprs(schema.exprs)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200699 except (QAPISchemaError, QAPIExprError), e:
Markus Armbruster2caba362013-07-27 17:41:56 +0200700 print >>sys.stderr, e
701 exit(1)
702
Michael Roth0f923be2011-07-19 14:50:39 -0500703def parse_args(typeinfo):
Eric Blakefe2a9302015-05-04 09:05:02 -0600704 if isinstance(typeinfo, str):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200705 struct = find_struct(typeinfo)
706 assert struct != None
707 typeinfo = struct['data']
708
Michael Roth0f923be2011-07-19 14:50:39 -0500709 for member in typeinfo:
710 argname = member
711 argentry = typeinfo[member]
712 optional = False
Michael Roth0f923be2011-07-19 14:50:39 -0500713 if member.startswith('*'):
714 argname = member[1:]
715 optional = True
Eric Blake6b5abc72015-05-04 09:05:33 -0600716 # Todo: allow argentry to be OrderedDict, for providing the
717 # value of an optional argument.
718 yield (argname, argentry, optional)
Michael Roth0f923be2011-07-19 14:50:39 -0500719
Michael Roth0f923be2011-07-19 14:50:39 -0500720def camel_case(name):
721 new_name = ''
722 first = True
723 for ch in name:
724 if ch in ['_', '-']:
725 first = True
726 elif first:
727 new_name += ch.upper()
728 first = False
729 else:
730 new_name += ch.lower()
731 return new_name
732
Markus Armbruster849bc532015-05-14 06:50:53 -0600733# ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
734# ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
735# ENUM24_Name -> ENUM24_NAME
736def camel_to_upper(value):
737 c_fun_str = c_name(value, False)
738 if value.isupper():
739 return c_fun_str
740
741 new_name = ''
742 l = len(c_fun_str)
743 for i in range(l):
744 c = c_fun_str[i]
745 # When c is upper and no "_" appears before, do more checks
746 if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
747 # Case 1: next string is lower
748 # Case 2: previous string is digit
749 if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
750 c_fun_str[i - 1].isdigit():
751 new_name += '_'
752 new_name += c
753 return new_name.lstrip('_').upper()
754
755def c_enum_const(type_name, const_name):
756 return camel_to_upper(type_name + '_' + const_name)
757
Eric Blake18df5152015-05-14 06:50:48 -0600758c_name_trans = string.maketrans('.-', '__')
Markus Armbruster47299262015-05-14 06:50:47 -0600759
Eric Blakec6405b52015-05-14 06:50:55 -0600760# Map @name to a valid C identifier.
761# If @protect, avoid returning certain ticklish identifiers (like
762# C keywords) by prepending "q_".
763#
764# Used for converting 'name' from a 'name':'type' qapi definition
765# into a generated struct member, as well as converting type names
766# into substrings of a generated C function name.
767# '__a.b_c' -> '__a_b_c', 'x-foo' -> 'x_foo'
768# protect=True: 'int' -> 'q_int'; protect=False: 'int' -> 'int'
Eric Blake18df5152015-05-14 06:50:48 -0600769def c_name(name, protect=True):
Blue Swirl427a1a22012-07-30 15:46:55 +0000770 # ANSI X3J11/88-090, 3.1.1
771 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
772 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
773 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
774 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
775 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
776 # ISO/IEC 9899:1999, 6.4.1
777 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
778 # ISO/IEC 9899:2011, 6.4.1
779 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
780 '_Static_assert', '_Thread_local'])
781 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
782 # excluding _.*
783 gcc_words = set(['asm', 'typeof'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400784 # C++ ISO/IEC 14882:2003 2.11
785 cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
786 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
787 'namespace', 'new', 'operator', 'private', 'protected',
788 'public', 'reinterpret_cast', 'static_cast', 'template',
789 'this', 'throw', 'true', 'try', 'typeid', 'typename',
790 'using', 'virtual', 'wchar_t',
791 # alternative representations
792 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
793 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
Paolo Bonzini10577252012-09-19 16:31:07 +0200794 # namespace pollution:
Max Reitz8592a542013-12-20 19:28:18 +0100795 polluted_words = set(['unix', 'errno'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400796 if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
Blue Swirl427a1a22012-07-30 15:46:55 +0000797 return "q_" + name
Eric Blake18df5152015-05-14 06:50:48 -0600798 return name.translate(c_name_trans)
Michael Roth0f923be2011-07-19 14:50:39 -0500799
Eric Blakec6405b52015-05-14 06:50:55 -0600800# Map type @name to the C typedef name for the list form.
801#
802# ['Name'] -> 'NameList', ['x-Foo'] -> 'x_FooList', ['int'] -> 'intList'
Michael Roth0f923be2011-07-19 14:50:39 -0500803def c_list_type(name):
Eric Blakec6405b52015-05-14 06:50:55 -0600804 return type_name(name) + 'List'
Michael Roth0f923be2011-07-19 14:50:39 -0500805
Eric Blakec6405b52015-05-14 06:50:55 -0600806# Map type @value to the C typedef form.
807#
808# Used for converting 'type' from a 'member':'type' qapi definition
809# into the alphanumeric portion of the type for a generated C parameter,
810# as well as generated C function names. See c_type() for the rest of
811# the conversion such as adding '*' on pointer types.
812# 'int' -> 'int', '[x-Foo]' -> 'x_FooList', '__a.b_c' -> '__a_b_c'
Eric Blaked5573442015-05-14 06:50:54 -0600813def type_name(value):
814 if type(value) == list:
815 return c_list_type(value[0])
Eric Blakec6405b52015-05-14 06:50:55 -0600816 if value in builtin_types.keys():
817 return value
818 return c_name(value)
Michael Roth0f923be2011-07-19 14:50:39 -0500819
Eric Blakefd41dd42015-05-04 09:05:25 -0600820def add_name(name, info, meta, implicit = False):
Eric Blake4dc2e692015-05-04 09:05:17 -0600821 global all_names
Eric Blakefd41dd42015-05-04 09:05:25 -0600822 check_name(info, "'%s'" % meta, name)
Eric Blake4dc2e692015-05-04 09:05:17 -0600823 if name in all_names:
824 raise QAPIExprError(info,
825 "%s '%s' is already defined"
826 % (all_names[name], name))
827 if not implicit and name[-4:] == 'Kind':
828 raise QAPIExprError(info,
829 "%s '%s' should not end in 'Kind'"
830 % (meta, name))
831 all_names[name] = meta
Kevin Wolfb35284e2013-07-01 16:31:51 +0200832
Eric Blake4dc2e692015-05-04 09:05:17 -0600833def add_struct(definition, info):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200834 global struct_types
Eric Blakefd41dd42015-05-04 09:05:25 -0600835 name = definition['struct']
836 add_name(name, info, 'struct')
Kevin Wolfb35284e2013-07-01 16:31:51 +0200837 struct_types.append(definition)
838
839def find_struct(name):
840 global struct_types
841 for struct in struct_types:
Eric Blakefd41dd42015-05-04 09:05:25 -0600842 if struct['struct'] == name:
Kevin Wolfb35284e2013-07-01 16:31:51 +0200843 return struct
844 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500845
Eric Blake4dc2e692015-05-04 09:05:17 -0600846def add_union(definition, info):
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200847 global union_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600848 name = definition['union']
849 add_name(name, info, 'union')
Eric Blakeab916fa2015-05-04 09:05:13 -0600850 union_types.append(definition)
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200851
852def find_union(name):
853 global union_types
854 for union in union_types:
855 if union['union'] == name:
856 return union
857 return None
858
Eric Blake4dc2e692015-05-04 09:05:17 -0600859def add_enum(name, info, enum_values = None, implicit = False):
Michael Roth0f923be2011-07-19 14:50:39 -0500860 global enum_types
Eric Blake4dc2e692015-05-04 09:05:17 -0600861 add_name(name, info, 'enum', implicit)
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800862 enum_types.append({"enum_name": name, "enum_values": enum_values})
863
864def find_enum(name):
865 global enum_types
866 for enum in enum_types:
867 if enum['enum_name'] == name:
868 return enum
869 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500870
871def is_enum(name):
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800872 return find_enum(name) != None
Michael Roth0f923be2011-07-19 14:50:39 -0500873
Amos Kong05dfb262014-06-10 19:25:53 +0800874eatspace = '\033EATSPACE.'
Eric Blaked5573442015-05-14 06:50:54 -0600875pointer_suffix = ' *' + eatspace
Amos Kong05dfb262014-06-10 19:25:53 +0800876
Eric Blakec6405b52015-05-14 06:50:55 -0600877# Map type @name to its C type expression.
878# If @is_param, const-qualify the string type.
879#
880# This function is used for computing the full C type of 'member':'name'.
Amos Kong05dfb262014-06-10 19:25:53 +0800881# A special suffix is added in c_type() for pointer types, and it's
882# stripped in mcgen(). So please notice this when you check the return
883# value of c_type() outside mcgen().
Eric Blaked5573442015-05-14 06:50:54 -0600884def c_type(value, is_param=False):
885 if value == 'str':
Amos Kong0d14eeb2014-06-10 19:25:52 +0800886 if is_param:
Eric Blaked5573442015-05-14 06:50:54 -0600887 return 'const char' + pointer_suffix
888 return 'char' + pointer_suffix
Amos Kong05dfb262014-06-10 19:25:53 +0800889
Eric Blaked5573442015-05-14 06:50:54 -0600890 elif value == 'int':
Michael Roth0f923be2011-07-19 14:50:39 -0500891 return 'int64_t'
Eric Blaked5573442015-05-14 06:50:54 -0600892 elif (value == 'int8' or value == 'int16' or value == 'int32' or
893 value == 'int64' or value == 'uint8' or value == 'uint16' or
894 value == 'uint32' or value == 'uint64'):
895 return value + '_t'
896 elif value == 'size':
Laszlo Ersek092705d2012-07-17 16:17:07 +0200897 return 'uint64_t'
Eric Blaked5573442015-05-14 06:50:54 -0600898 elif value == 'bool':
Michael Roth0f923be2011-07-19 14:50:39 -0500899 return 'bool'
Eric Blaked5573442015-05-14 06:50:54 -0600900 elif value == 'number':
Michael Roth0f923be2011-07-19 14:50:39 -0500901 return 'double'
Eric Blaked5573442015-05-14 06:50:54 -0600902 elif type(value) == list:
903 return c_list_type(value[0]) + pointer_suffix
904 elif is_enum(value):
Eric Blakec6405b52015-05-14 06:50:55 -0600905 return c_name(value)
Eric Blaked5573442015-05-14 06:50:54 -0600906 elif value == None:
Michael Roth0f923be2011-07-19 14:50:39 -0500907 return 'void'
Eric Blaked5573442015-05-14 06:50:54 -0600908 elif value in events:
909 return camel_case(value) + 'Event' + pointer_suffix
Michael Roth0f923be2011-07-19 14:50:39 -0500910 else:
Eric Blaked5573442015-05-14 06:50:54 -0600911 # complex type name
912 assert isinstance(value, str) and value != ""
Eric Blakec6405b52015-05-14 06:50:55 -0600913 return c_name(value) + pointer_suffix
Amos Kong05dfb262014-06-10 19:25:53 +0800914
Eric Blaked5573442015-05-14 06:50:54 -0600915def is_c_ptr(value):
916 return c_type(value).endswith(pointer_suffix)
Michael Roth0f923be2011-07-19 14:50:39 -0500917
918def genindent(count):
919 ret = ""
920 for i in range(count):
921 ret += " "
922 return ret
923
924indent_level = 0
925
926def push_indent(indent_amount=4):
927 global indent_level
928 indent_level += indent_amount
929
930def pop_indent(indent_amount=4):
931 global indent_level
932 indent_level -= indent_amount
933
934def cgen(code, **kwds):
935 indent = genindent(indent_level)
936 lines = code.split('\n')
937 lines = map(lambda x: indent + x, lines)
938 return '\n'.join(lines) % kwds + '\n'
939
940def mcgen(code, **kwds):
Amos Kong05dfb262014-06-10 19:25:53 +0800941 raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
942 return re.sub(re.escape(eatspace) + ' *', '', raw)
Michael Roth0f923be2011-07-19 14:50:39 -0500943
944def basename(filename):
945 return filename.split("/")[-1]
946
947def guardname(filename):
Michael Rothd8e1f212011-11-29 16:47:48 -0600948 guard = basename(filename).rsplit(".", 1)[0]
949 for substr in [".", " ", "-"]:
950 guard = guard.replace(substr, "_")
951 return guard.upper() + '_H'
Michael Rothc0afa9c2013-05-10 17:46:00 -0500952
953def guardstart(name):
954 return mcgen('''
955
956#ifndef %(name)s
957#define %(name)s
958
959''',
960 name=guardname(name))
961
962def guardend(name):
963 return mcgen('''
964
965#endif /* %(name)s */
966
967''',
968 name=guardname(name))
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200969
970def parse_command_line(extra_options = "", extra_long_options = []):
971
972 try:
973 opts, args = getopt.gnu_getopt(sys.argv[1:],
Markus Armbruster16d80f62015-04-02 13:32:16 +0200974 "chp:o:" + extra_options,
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200975 ["source", "header", "prefix=",
Markus Armbruster16d80f62015-04-02 13:32:16 +0200976 "output-dir="] + extra_long_options)
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200977 except getopt.GetoptError, err:
Markus Armbrusterb4540962015-04-02 13:17:34 +0200978 print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200979 sys.exit(1)
980
981 output_dir = ""
982 prefix = ""
983 do_c = False
984 do_h = False
985 extra_opts = []
986
987 for oa in opts:
988 o, a = oa
989 if o in ("-p", "--prefix"):
990 prefix = a
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200991 elif o in ("-o", "--output-dir"):
992 output_dir = a + "/"
993 elif o in ("-c", "--source"):
994 do_c = True
995 elif o in ("-h", "--header"):
996 do_h = True
997 else:
998 extra_opts.append(oa)
999
1000 if not do_c and not do_h:
1001 do_c = True
1002 do_h = True
1003
Markus Armbruster16d80f62015-04-02 13:32:16 +02001004 if len(args) != 1:
1005 print >>sys.stderr, "%s: need exactly one argument" % sys.argv[0]
Markus Armbrusterb4540962015-04-02 13:17:34 +02001006 sys.exit(1)
Markus Armbruster54414042015-06-09 16:22:45 +02001007 fname = args[0]
Markus Armbrusterb4540962015-04-02 13:17:34 +02001008
Markus Armbruster54414042015-06-09 16:22:45 +02001009 return (fname, output_dir, do_c, do_h, prefix, extra_opts)
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001010
1011def open_output(output_dir, do_c, do_h, prefix, c_file, h_file,
1012 c_comment, h_comment):
1013 c_file = output_dir + prefix + c_file
1014 h_file = output_dir + prefix + h_file
1015
1016 try:
1017 os.makedirs(output_dir)
1018 except os.error, e:
1019 if e.errno != errno.EEXIST:
1020 raise
1021
1022 def maybe_open(really, name, opt):
1023 if really:
1024 return open(name, opt)
1025 else:
1026 import StringIO
1027 return StringIO.StringIO()
1028
1029 fdef = maybe_open(do_c, c_file, 'w')
1030 fdecl = maybe_open(do_h, h_file, 'w')
1031
1032 fdef.write(mcgen('''
1033/* AUTOMATICALLY GENERATED, DO NOT MODIFY */
1034%(comment)s
1035''',
1036 comment = c_comment))
1037
1038 fdecl.write(mcgen('''
1039/* AUTOMATICALLY GENERATED, DO NOT MODIFY */
1040%(comment)s
1041#ifndef %(guard)s
1042#define %(guard)s
1043
1044''',
1045 comment = h_comment, guard = guardname(h_file)))
1046
1047 return (fdef, fdecl)
1048
1049def close_output(fdef, fdecl):
1050 fdecl.write('''
1051#endif
1052''')
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001053 fdecl.close()
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001054 fdef.close()