blob: bbeae4d322723f4c99458edaab6ce9ed46570103 [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
Markus Armbruster00e4b282015-06-10 10:04:36 +020068#
69# Parsing the schema into expressions
70#
71
Lluís Vilanovaa719a272014-05-07 20:46:15 +020072def error_path(parent):
73 res = ""
74 while parent:
75 res = ("In file included from %s:%d:\n" % (parent['file'],
76 parent['line'])) + res
77 parent = parent['parent']
78 return res
79
Markus Armbruster2caba362013-07-27 17:41:56 +020080class QAPISchemaError(Exception):
81 def __init__(self, schema, msg):
Markus Armbruster54414042015-06-09 16:22:45 +020082 self.fname = schema.fname
Markus Armbruster2caba362013-07-27 17:41:56 +020083 self.msg = msg
Wenchao Xia515b9432014-03-04 18:44:33 -080084 self.col = 1
85 self.line = schema.line
86 for ch in schema.src[schema.line_pos:schema.pos]:
87 if ch == '\t':
Markus Armbruster2caba362013-07-27 17:41:56 +020088 self.col = (self.col + 7) % 8 + 1
89 else:
90 self.col += 1
Markus Armbruster54414042015-06-09 16:22:45 +020091 self.info = schema.incl_info
Markus Armbruster2caba362013-07-27 17:41:56 +020092
93 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020094 return error_path(self.info) + \
Markus Armbruster54414042015-06-09 16:22:45 +020095 "%s:%d:%d: %s" % (self.fname, self.line, self.col, self.msg)
Markus Armbruster2caba362013-07-27 17:41:56 +020096
Wenchao Xiab86b05e2014-03-04 18:44:34 -080097class QAPIExprError(Exception):
98 def __init__(self, expr_info, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020099 self.info = expr_info
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800100 self.msg = msg
101
102 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200103 return error_path(self.info['parent']) + \
104 "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800105
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200106class QAPISchema:
Michael Roth0f923be2011-07-19 14:50:39 -0500107
Markus Armbrustera1366082015-06-09 16:54:09 +0200108 def __init__(self, fp, previously_included = [], incl_info = None):
Markus Armbruster54414042015-06-09 16:22:45 +0200109 abs_fname = os.path.abspath(fp.name)
Markus Armbruster8608d252015-06-09 18:32:29 +0200110 fname = fp.name
Markus Armbruster54414042015-06-09 16:22:45 +0200111 self.fname = fname
Markus Armbruster54414042015-06-09 16:22:45 +0200112 previously_included.append(abs_fname)
113 self.incl_info = incl_info
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200114 self.src = fp.read()
115 if self.src == '' or self.src[-1] != '\n':
116 self.src += '\n'
117 self.cursor = 0
Wenchao Xia515b9432014-03-04 18:44:33 -0800118 self.line = 1
119 self.line_pos = 0
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200120 self.exprs = []
121 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500122
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200123 while self.tok != None:
Markus Armbruster54414042015-06-09 16:22:45 +0200124 expr_info = {'file': fname, 'line': self.line,
125 'parent': self.incl_info}
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200126 expr = self.get_expr(False)
127 if isinstance(expr, dict) and "include" in expr:
128 if len(expr) != 1:
129 raise QAPIExprError(expr_info, "Invalid 'include' directive")
130 include = expr["include"]
131 if not isinstance(include, str):
132 raise QAPIExprError(expr_info,
133 'Expected a file name (string), got: %s'
134 % include)
Markus Armbruster54414042015-06-09 16:22:45 +0200135 incl_abs_fname = os.path.join(os.path.dirname(abs_fname),
136 include)
Markus Armbrustera1366082015-06-09 16:54:09 +0200137 # catch inclusion cycle
138 inf = expr_info
139 while inf:
140 if incl_abs_fname == os.path.abspath(inf['file']):
Stefan Hajnoczi7ac9a9d2014-08-27 12:08:51 +0100141 raise QAPIExprError(expr_info, "Inclusion loop for %s"
142 % include)
Markus Armbrustera1366082015-06-09 16:54:09 +0200143 inf = inf['parent']
Benoît Canet24fd8482014-05-16 12:51:56 +0200144 # skip multiple include of the same file
Markus Armbruster54414042015-06-09 16:22:45 +0200145 if incl_abs_fname in previously_included:
Benoît Canet24fd8482014-05-16 12:51:56 +0200146 continue
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200147 try:
Markus Armbruster54414042015-06-09 16:22:45 +0200148 fobj = open(incl_abs_fname, 'r')
Luiz Capitulino34788812014-05-20 13:50:19 -0400149 except IOError, e:
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200150 raise QAPIExprError(expr_info,
151 '%s: %s' % (e.strerror, include))
Markus Armbrustera1366082015-06-09 16:54:09 +0200152 exprs_include = QAPISchema(fobj, previously_included,
153 expr_info)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200154 self.exprs.extend(exprs_include.exprs)
155 else:
156 expr_elem = {'expr': expr,
157 'info': expr_info}
158 self.exprs.append(expr_elem)
Michael Roth0f923be2011-07-19 14:50:39 -0500159
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200160 def accept(self):
161 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200162 self.tok = self.src[self.cursor]
Markus Armbruster2caba362013-07-27 17:41:56 +0200163 self.pos = self.cursor
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200164 self.cursor += 1
165 self.val = None
Michael Roth0f923be2011-07-19 14:50:39 -0500166
Markus Armbrusterf1a145e2013-07-27 17:42:01 +0200167 if self.tok == '#':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200168 self.cursor = self.src.find('\n', self.cursor)
169 elif self.tok in ['{', '}', ':', ',', '[', ']']:
170 return
171 elif self.tok == "'":
172 string = ''
173 esc = False
174 while True:
175 ch = self.src[self.cursor]
176 self.cursor += 1
177 if ch == '\n':
Markus Armbruster2caba362013-07-27 17:41:56 +0200178 raise QAPISchemaError(self,
179 'Missing terminating "\'"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200180 if esc:
Eric Blakea7f59662015-05-04 09:05:36 -0600181 if ch == 'b':
182 string += '\b'
183 elif ch == 'f':
184 string += '\f'
185 elif ch == 'n':
186 string += '\n'
187 elif ch == 'r':
188 string += '\r'
189 elif ch == 't':
190 string += '\t'
191 elif ch == 'u':
192 value = 0
193 for x in range(0, 4):
194 ch = self.src[self.cursor]
195 self.cursor += 1
196 if ch not in "0123456789abcdefABCDEF":
197 raise QAPISchemaError(self,
198 '\\u escape needs 4 '
199 'hex digits')
200 value = (value << 4) + int(ch, 16)
201 # If Python 2 and 3 didn't disagree so much on
202 # how to handle Unicode, then we could allow
203 # Unicode string defaults. But most of QAPI is
204 # ASCII-only, so we aren't losing much for now.
205 if not value or value > 0x7f:
206 raise QAPISchemaError(self,
207 'For now, \\u escape '
208 'only supports non-zero '
209 'values up to \\u007f')
210 string += chr(value)
211 elif ch in "\\/'\"":
212 string += ch
213 else:
214 raise QAPISchemaError(self,
215 "Unknown escape \\%s" %ch)
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200216 esc = False
217 elif ch == "\\":
218 esc = True
219 elif ch == "'":
220 self.val = string
221 return
222 else:
223 string += ch
Markus Armbrustere565d932015-06-10 08:24:58 +0200224 elif self.src.startswith("true", self.pos):
225 self.val = True
226 self.cursor += 3
227 return
228 elif self.src.startswith("false", self.pos):
229 self.val = False
230 self.cursor += 4
231 return
232 elif self.src.startswith("null", self.pos):
233 self.val = None
234 self.cursor += 3
235 return
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200236 elif self.tok == '\n':
237 if self.cursor == len(self.src):
238 self.tok = None
239 return
Wenchao Xia515b9432014-03-04 18:44:33 -0800240 self.line += 1
241 self.line_pos = self.cursor
Markus Armbruster9213aa52013-07-27 17:41:57 +0200242 elif not self.tok.isspace():
243 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
Michael Roth0f923be2011-07-19 14:50:39 -0500244
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200245 def get_members(self):
246 expr = OrderedDict()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200247 if self.tok == '}':
248 self.accept()
249 return expr
250 if self.tok != "'":
251 raise QAPISchemaError(self, 'Expected string or "}"')
252 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200253 key = self.val
254 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200255 if self.tok != ':':
256 raise QAPISchemaError(self, 'Expected ":"')
257 self.accept()
Wenchao Xia4b359912014-03-04 18:44:32 -0800258 if key in expr:
259 raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200260 expr[key] = self.get_expr(True)
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200261 if self.tok == '}':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200262 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200263 return expr
264 if self.tok != ',':
265 raise QAPISchemaError(self, 'Expected "," or "}"')
266 self.accept()
267 if self.tok != "'":
268 raise QAPISchemaError(self, 'Expected string')
Michael Roth0f923be2011-07-19 14:50:39 -0500269
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200270 def get_values(self):
271 expr = []
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200272 if self.tok == ']':
273 self.accept()
274 return expr
Fam Zhenge53188a2015-05-04 09:05:18 -0600275 if not self.tok in "{['tfn":
276 raise QAPISchemaError(self, 'Expected "{", "[", "]", string, '
277 'boolean or "null"')
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200278 while True:
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200279 expr.append(self.get_expr(True))
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200280 if self.tok == ']':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200281 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200282 return expr
283 if self.tok != ',':
284 raise QAPISchemaError(self, 'Expected "," or "]"')
285 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500286
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200287 def get_expr(self, nested):
288 if self.tok != '{' and not nested:
289 raise QAPISchemaError(self, 'Expected "{"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200290 if self.tok == '{':
291 self.accept()
292 expr = self.get_members()
293 elif self.tok == '[':
294 self.accept()
295 expr = self.get_values()
Fam Zhenge53188a2015-05-04 09:05:18 -0600296 elif self.tok in "'tfn":
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200297 expr = self.val
298 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200299 else:
300 raise QAPISchemaError(self, 'Expected "{", "[" or string')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200301 return expr
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200302
Markus Armbruster00e4b282015-06-10 10:04:36 +0200303#
304# Semantic analysis of schema expressions
305#
306
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800307def find_base_fields(base):
308 base_struct_define = find_struct(base)
309 if not base_struct_define:
310 return None
311 return base_struct_define['data']
312
Eric Blake811d04f2015-05-04 09:05:10 -0600313# Return the qtype of an alternate branch, or None on error.
314def find_alternate_member_qtype(qapi_type):
Eric Blake44bd1272015-05-04 09:05:08 -0600315 if builtin_types.has_key(qapi_type):
316 return builtin_types[qapi_type]
317 elif find_struct(qapi_type):
318 return "QTYPE_QDICT"
319 elif find_enum(qapi_type):
320 return "QTYPE_QSTRING"
Eric Blake811d04f2015-05-04 09:05:10 -0600321 elif find_union(qapi_type):
322 return "QTYPE_QDICT"
Eric Blake44bd1272015-05-04 09:05:08 -0600323 return None
324
Wenchao Xiabceae762014-03-06 17:08:56 -0800325# Return the discriminator enum define if discriminator is specified as an
326# enum type, otherwise return None.
327def discriminator_find_enum_define(expr):
328 base = expr.get('base')
329 discriminator = expr.get('discriminator')
330
331 if not (discriminator and base):
332 return None
333
334 base_fields = find_base_fields(base)
335 if not base_fields:
336 return None
337
338 discriminator_type = base_fields.get(discriminator)
339 if not discriminator_type:
340 return None
341
342 return find_enum(discriminator_type)
343
Markus Armbrusterd90675f2015-07-31 11:33:52 +0200344# FIXME should enforce "other than downstream extensions [...], all
345# names should begin with a letter".
Eric Blakec9e0a792015-05-04 09:05:22 -0600346valid_name = re.compile('^[a-zA-Z_][a-zA-Z0-9_.-]*$')
347def check_name(expr_info, source, name, allow_optional = False,
348 enum_member = False):
349 global valid_name
350 membername = name
351
352 if not isinstance(name, str):
353 raise QAPIExprError(expr_info,
354 "%s requires a string name" % source)
355 if name.startswith('*'):
356 membername = name[1:]
357 if not allow_optional:
358 raise QAPIExprError(expr_info,
359 "%s does not allow optional name '%s'"
360 % (source, name))
361 # Enum members can start with a digit, because the generated C
362 # code always prefixes it with the enum name
363 if enum_member:
364 membername = '_' + membername
365 if not valid_name.match(membername):
366 raise QAPIExprError(expr_info,
367 "%s uses invalid name '%s'" % (source, name))
368
Markus Armbruster00e4b282015-06-10 10:04:36 +0200369def add_name(name, info, meta, implicit = False):
370 global all_names
371 check_name(info, "'%s'" % meta, name)
Markus Armbrusterd90675f2015-07-31 11:33:52 +0200372 # FIXME should reject names that differ only in '_' vs. '.'
373 # vs. '-', because they're liable to clash in generated C.
Markus Armbruster00e4b282015-06-10 10:04:36 +0200374 if name in all_names:
375 raise QAPIExprError(info,
376 "%s '%s' is already defined"
377 % (all_names[name], name))
378 if not implicit and name[-4:] == 'Kind':
379 raise QAPIExprError(info,
380 "%s '%s' should not end in 'Kind'"
381 % (meta, name))
382 all_names[name] = meta
383
384def add_struct(definition, info):
385 global struct_types
386 name = definition['struct']
387 add_name(name, info, 'struct')
388 struct_types.append(definition)
389
390def find_struct(name):
391 global struct_types
392 for struct in struct_types:
393 if struct['struct'] == name:
394 return struct
395 return None
396
397def add_union(definition, info):
398 global union_types
399 name = definition['union']
400 add_name(name, info, 'union')
401 union_types.append(definition)
402
403def find_union(name):
404 global union_types
405 for union in union_types:
406 if union['union'] == name:
407 return union
408 return None
409
410def add_enum(name, info, enum_values = None, implicit = False):
411 global enum_types
412 add_name(name, info, 'enum', implicit)
413 enum_types.append({"enum_name": name, "enum_values": enum_values})
414
415def find_enum(name):
416 global enum_types
417 for enum in enum_types:
418 if enum['enum_name'] == name:
419 return enum
420 return None
421
422def is_enum(name):
423 return find_enum(name) != None
424
Eric Blakedd883c62015-05-04 09:05:21 -0600425def check_type(expr_info, source, value, allow_array = False,
Eric Blake2cbf0992015-05-04 09:05:24 -0600426 allow_dict = False, allow_optional = False,
427 allow_star = False, allow_metas = []):
Eric Blakedd883c62015-05-04 09:05:21 -0600428 global all_names
429 orig_value = value
430
431 if value is None:
432 return
433
Eric Blake2cbf0992015-05-04 09:05:24 -0600434 if allow_star and value == '**':
Eric Blakedd883c62015-05-04 09:05:21 -0600435 return
436
437 # Check if array type for value is okay
438 if isinstance(value, list):
439 if not allow_array:
440 raise QAPIExprError(expr_info,
441 "%s cannot be an array" % source)
442 if len(value) != 1 or not isinstance(value[0], str):
443 raise QAPIExprError(expr_info,
444 "%s: array type must contain single type name"
445 % source)
446 value = value[0]
447 orig_value = "array of %s" %value
448
449 # Check if type name for value is okay
450 if isinstance(value, str):
Eric Blake2cbf0992015-05-04 09:05:24 -0600451 if value == '**':
452 raise QAPIExprError(expr_info,
453 "%s uses '**' but did not request 'gen':false"
454 % source)
Eric Blakedd883c62015-05-04 09:05:21 -0600455 if not value in all_names:
456 raise QAPIExprError(expr_info,
457 "%s uses unknown type '%s'"
458 % (source, orig_value))
459 if not all_names[value] in allow_metas:
460 raise QAPIExprError(expr_info,
461 "%s cannot use %s type '%s'"
462 % (source, all_names[value], orig_value))
463 return
464
465 # value is a dictionary, check that each member is okay
466 if not isinstance(value, OrderedDict):
467 raise QAPIExprError(expr_info,
468 "%s should be a dictionary" % source)
469 if not allow_dict:
470 raise QAPIExprError(expr_info,
471 "%s should be a type name" % source)
472 for (key, arg) in value.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600473 check_name(expr_info, "Member of %s" % source, key,
474 allow_optional=allow_optional)
Eric Blake6b5abc72015-05-04 09:05:33 -0600475 # Todo: allow dictionaries to represent default values of
476 # an optional argument.
Eric Blakedd883c62015-05-04 09:05:21 -0600477 check_type(expr_info, "Member '%s' of %s" % (key, source), arg,
Eric Blake6b5abc72015-05-04 09:05:33 -0600478 allow_array=True, allow_star=allow_star,
Eric Blakedd883c62015-05-04 09:05:21 -0600479 allow_metas=['built-in', 'union', 'alternate', 'struct',
Eric Blake6b5abc72015-05-04 09:05:33 -0600480 'enum'])
Eric Blakedd883c62015-05-04 09:05:21 -0600481
Eric Blakeff55d722015-05-04 09:05:37 -0600482def check_member_clash(expr_info, base_name, data, source = ""):
483 base = find_struct(base_name)
484 assert base
485 base_members = base['data']
486 for key in data.keys():
487 if key.startswith('*'):
488 key = key[1:]
489 if key in base_members or "*" + key in base_members:
490 raise QAPIExprError(expr_info,
491 "Member name '%s'%s clashes with base '%s'"
492 % (key, source, base_name))
493 if base.get('base'):
494 check_member_clash(expr_info, base['base'], data, source)
495
Eric Blakedd883c62015-05-04 09:05:21 -0600496def check_command(expr, expr_info):
497 name = expr['command']
Eric Blake2cbf0992015-05-04 09:05:24 -0600498 allow_star = expr.has_key('gen')
499
Eric Blakedd883c62015-05-04 09:05:21 -0600500 check_type(expr_info, "'data' for command '%s'" % name,
Eric Blakec9e0a792015-05-04 09:05:22 -0600501 expr.get('data'), allow_dict=True, allow_optional=True,
Markus Armbruster315932b2015-07-01 10:12:24 +0200502 allow_metas=['struct'], allow_star=allow_star)
Eric Blake10d4d992015-05-04 09:05:23 -0600503 returns_meta = ['union', 'struct']
504 if name in returns_whitelist:
505 returns_meta += ['built-in', 'alternate', 'enum']
Eric Blakedd883c62015-05-04 09:05:21 -0600506 check_type(expr_info, "'returns' for command '%s'" % name,
507 expr.get('returns'), allow_array=True, allow_dict=True,
Eric Blake2cbf0992015-05-04 09:05:24 -0600508 allow_optional=True, allow_metas=returns_meta,
509 allow_star=allow_star)
Eric Blakedd883c62015-05-04 09:05:21 -0600510
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200511def check_event(expr, expr_info):
Eric Blake4dc2e692015-05-04 09:05:17 -0600512 global events
513 name = expr['event']
Eric Blake4dc2e692015-05-04 09:05:17 -0600514
515 if name.upper() == 'MAX':
516 raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created")
517 events.append(name)
Eric Blakedd883c62015-05-04 09:05:21 -0600518 check_type(expr_info, "'data' for event '%s'" % name,
Eric Blakec9e0a792015-05-04 09:05:22 -0600519 expr.get('data'), allow_dict=True, allow_optional=True,
Markus Armbruster315932b2015-07-01 10:12:24 +0200520 allow_metas=['struct'])
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200521
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800522def check_union(expr, expr_info):
523 name = expr['union']
524 base = expr.get('base')
525 discriminator = expr.get('discriminator')
526 members = expr['data']
Eric Blake44bd1272015-05-04 09:05:08 -0600527 values = { 'MAX': '(automatic)' }
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800528
Eric Blakefd41dd42015-05-04 09:05:25 -0600529 # If the object has a member 'base', its value must name a struct,
Eric Blakea8d4a2e2015-05-04 09:05:07 -0600530 # and there must be a discriminator.
531 if base is not None:
532 if discriminator is None:
533 raise QAPIExprError(expr_info,
534 "Union '%s' requires a discriminator to go "
535 "along with base" %name)
Eric Blake44bd1272015-05-04 09:05:08 -0600536
Eric Blake811d04f2015-05-04 09:05:10 -0600537 # Two types of unions, determined by discriminator.
Eric Blake811d04f2015-05-04 09:05:10 -0600538
539 # With no discriminator it is a simple union.
540 if discriminator is None:
Eric Blake44bd1272015-05-04 09:05:08 -0600541 enum_define = None
Eric Blakedd883c62015-05-04 09:05:21 -0600542 allow_metas=['built-in', 'union', 'alternate', 'struct', 'enum']
Eric Blake44bd1272015-05-04 09:05:08 -0600543 if base is not None:
544 raise QAPIExprError(expr_info,
Eric Blake811d04f2015-05-04 09:05:10 -0600545 "Simple union '%s' must not have a base"
Eric Blake44bd1272015-05-04 09:05:08 -0600546 % name)
547
548 # Else, it's a flat union.
549 else:
550 # The object must have a string member 'base'.
551 if not isinstance(base, str):
552 raise QAPIExprError(expr_info,
553 "Flat union '%s' must have a string base field"
554 % name)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800555 base_fields = find_base_fields(base)
556 if not base_fields:
557 raise QAPIExprError(expr_info,
Eric Blakefd41dd42015-05-04 09:05:25 -0600558 "Base '%s' is not a valid struct"
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800559 % base)
560
Eric Blakec9e0a792015-05-04 09:05:22 -0600561 # The value of member 'discriminator' must name a non-optional
Eric Blakefd41dd42015-05-04 09:05:25 -0600562 # member of the base struct.
Eric Blakec9e0a792015-05-04 09:05:22 -0600563 check_name(expr_info, "Discriminator of flat union '%s'" % name,
564 discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800565 discriminator_type = base_fields.get(discriminator)
566 if not discriminator_type:
567 raise QAPIExprError(expr_info,
568 "Discriminator '%s' is not a member of base "
Eric Blakefd41dd42015-05-04 09:05:25 -0600569 "struct '%s'"
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800570 % (discriminator, base))
571 enum_define = find_enum(discriminator_type)
Eric Blakedd883c62015-05-04 09:05:21 -0600572 allow_metas=['struct']
Wenchao Xia52230702014-03-04 18:44:39 -0800573 # Do not allow string discriminator
574 if not enum_define:
575 raise QAPIExprError(expr_info,
576 "Discriminator '%s' must be of enumeration "
577 "type" % discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800578
579 # Check every branch
580 for (key, value) in members.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600581 check_name(expr_info, "Member of union '%s'" % name, key)
582
Eric Blakedd883c62015-05-04 09:05:21 -0600583 # Each value must name a known type; furthermore, in flat unions,
Eric Blakeff55d722015-05-04 09:05:37 -0600584 # branches must be a struct with no overlapping member names
Eric Blakedd883c62015-05-04 09:05:21 -0600585 check_type(expr_info, "Member '%s' of union '%s'" % (key, name),
Markus Armbrusterf9a14272015-06-10 13:07:43 +0200586 value, allow_array=not base, allow_metas=allow_metas)
Eric Blakeff55d722015-05-04 09:05:37 -0600587 if base:
588 branch_struct = find_struct(value)
589 assert branch_struct
590 check_member_clash(expr_info, base, branch_struct['data'],
591 " of branch '%s'" % key)
Eric Blakedd883c62015-05-04 09:05:21 -0600592
Eric Blake44bd1272015-05-04 09:05:08 -0600593 # If the discriminator names an enum type, then all members
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800594 # of 'data' must also be members of the enum type.
Eric Blake44bd1272015-05-04 09:05:08 -0600595 if enum_define:
596 if not key in enum_define['enum_values']:
597 raise QAPIExprError(expr_info,
598 "Discriminator value '%s' is not found in "
599 "enum '%s'" %
600 (key, enum_define["enum_name"]))
601
602 # Otherwise, check for conflicts in the generated enum
603 else:
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600604 c_key = camel_to_upper(key)
Eric Blake44bd1272015-05-04 09:05:08 -0600605 if c_key in values:
606 raise QAPIExprError(expr_info,
607 "Union '%s' member '%s' clashes with '%s'"
608 % (name, key, values[c_key]))
609 values[c_key] = key
610
Eric Blake811d04f2015-05-04 09:05:10 -0600611def check_alternate(expr, expr_info):
Eric Blakeab916fa2015-05-04 09:05:13 -0600612 name = expr['alternate']
Eric Blake811d04f2015-05-04 09:05:10 -0600613 members = expr['data']
614 values = { 'MAX': '(automatic)' }
615 types_seen = {}
Eric Blake44bd1272015-05-04 09:05:08 -0600616
Eric Blake811d04f2015-05-04 09:05:10 -0600617 # Check every branch
618 for (key, value) in members.items():
Eric Blakec9e0a792015-05-04 09:05:22 -0600619 check_name(expr_info, "Member of alternate '%s'" % name, key)
620
Eric Blake811d04f2015-05-04 09:05:10 -0600621 # Check for conflicts in the generated enum
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600622 c_key = camel_to_upper(key)
Eric Blake811d04f2015-05-04 09:05:10 -0600623 if c_key in values:
624 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600625 "Alternate '%s' member '%s' clashes with '%s'"
626 % (name, key, values[c_key]))
Eric Blake811d04f2015-05-04 09:05:10 -0600627 values[c_key] = key
628
629 # Ensure alternates have no type conflicts.
Eric Blakedd883c62015-05-04 09:05:21 -0600630 check_type(expr_info, "Member '%s' of alternate '%s'" % (key, name),
631 value,
632 allow_metas=['built-in', 'union', 'struct', 'enum'])
Eric Blake811d04f2015-05-04 09:05:10 -0600633 qtype = find_alternate_member_qtype(value)
Eric Blakedd883c62015-05-04 09:05:21 -0600634 assert qtype
Eric Blake811d04f2015-05-04 09:05:10 -0600635 if qtype in types_seen:
636 raise QAPIExprError(expr_info,
Eric Blakeab916fa2015-05-04 09:05:13 -0600637 "Alternate '%s' member '%s' can't "
Eric Blake811d04f2015-05-04 09:05:10 -0600638 "be distinguished from member '%s'"
639 % (name, key, types_seen[qtype]))
640 types_seen[qtype] = key
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800641
Eric Blakecf393592015-05-04 09:05:04 -0600642def check_enum(expr, expr_info):
643 name = expr['enum']
644 members = expr.get('data')
645 values = { 'MAX': '(automatic)' }
646
647 if not isinstance(members, list):
648 raise QAPIExprError(expr_info,
649 "Enum '%s' requires an array for 'data'" % name)
650 for member in members:
Eric Blakec9e0a792015-05-04 09:05:22 -0600651 check_name(expr_info, "Member of enum '%s'" %name, member,
652 enum_member=True)
Markus Armbrusterfa6068a2015-05-14 06:50:49 -0600653 key = camel_to_upper(member)
Eric Blakecf393592015-05-04 09:05:04 -0600654 if key in values:
655 raise QAPIExprError(expr_info,
656 "Enum '%s' member '%s' clashes with '%s'"
657 % (name, member, values[key]))
658 values[key] = member
659
Eric Blakedd883c62015-05-04 09:05:21 -0600660def check_struct(expr, expr_info):
Eric Blakefd41dd42015-05-04 09:05:25 -0600661 name = expr['struct']
Eric Blakedd883c62015-05-04 09:05:21 -0600662 members = expr['data']
663
Eric Blakefd41dd42015-05-04 09:05:25 -0600664 check_type(expr_info, "'data' for struct '%s'" % name, members,
Eric Blakec9e0a792015-05-04 09:05:22 -0600665 allow_dict=True, allow_optional=True)
Eric Blakefd41dd42015-05-04 09:05:25 -0600666 check_type(expr_info, "'base' for struct '%s'" % name, expr.get('base'),
Eric Blakedd883c62015-05-04 09:05:21 -0600667 allow_metas=['struct'])
Eric Blakeff55d722015-05-04 09:05:37 -0600668 if expr.get('base'):
669 check_member_clash(expr_info, expr['base'], expr['data'])
Eric Blakedd883c62015-05-04 09:05:21 -0600670
Eric Blake0545f6b2015-05-04 09:05:15 -0600671def check_keys(expr_elem, meta, required, optional=[]):
672 expr = expr_elem['expr']
673 info = expr_elem['info']
674 name = expr[meta]
675 if not isinstance(name, str):
676 raise QAPIExprError(info,
677 "'%s' key must have a string value" % meta)
678 required = required + [ meta ]
679 for (key, value) in expr.items():
680 if not key in required and not key in optional:
681 raise QAPIExprError(info,
682 "Unknown key '%s' in %s '%s'"
683 % (key, meta, name))
Eric Blake2cbf0992015-05-04 09:05:24 -0600684 if (key == 'gen' or key == 'success-response') and value != False:
685 raise QAPIExprError(info,
686 "'%s' of %s '%s' should only use false value"
687 % (key, meta, name))
Eric Blake0545f6b2015-05-04 09:05:15 -0600688 for key in required:
689 if not expr.has_key(key):
690 raise QAPIExprError(info,
691 "Key '%s' is missing from %s '%s'"
692 % (key, meta, name))
693
Markus Armbruster4d076d62015-06-10 08:55:21 +0200694def check_exprs(exprs):
695 global all_names
696
697 # Learn the types and check for valid expression keys
698 for builtin in builtin_types.keys():
699 all_names[builtin] = 'built-in'
700 for expr_elem in exprs:
701 expr = expr_elem['expr']
702 info = expr_elem['info']
703 if expr.has_key('enum'):
704 check_keys(expr_elem, 'enum', ['data'])
705 add_enum(expr['enum'], info, expr['data'])
706 elif expr.has_key('union'):
707 check_keys(expr_elem, 'union', ['data'],
708 ['base', 'discriminator'])
709 add_union(expr, info)
710 elif expr.has_key('alternate'):
711 check_keys(expr_elem, 'alternate', ['data'])
712 add_name(expr['alternate'], info, 'alternate')
713 elif expr.has_key('struct'):
714 check_keys(expr_elem, 'struct', ['data'], ['base'])
715 add_struct(expr, info)
716 elif expr.has_key('command'):
717 check_keys(expr_elem, 'command', [],
718 ['data', 'returns', 'gen', 'success-response'])
719 add_name(expr['command'], info, 'command')
720 elif expr.has_key('event'):
721 check_keys(expr_elem, 'event', [], ['data'])
722 add_name(expr['event'], info, 'event')
723 else:
724 raise QAPIExprError(expr_elem['info'],
725 "Expression is missing metatype")
726
727 # Try again for hidden UnionKind enum
728 for expr_elem in exprs:
729 expr = expr_elem['expr']
730 if expr.has_key('union'):
731 if not discriminator_find_enum_define(expr):
732 add_enum('%sKind' % expr['union'], expr_elem['info'],
733 implicit=True)
734 elif expr.has_key('alternate'):
735 add_enum('%sKind' % expr['alternate'], expr_elem['info'],
736 implicit=True)
737
738 # Validate that exprs make sense
739 for expr_elem in exprs:
740 expr = expr_elem['expr']
741 info = expr_elem['info']
742
743 if expr.has_key('enum'):
744 check_enum(expr, info)
745 elif expr.has_key('union'):
746 check_union(expr, info)
747 elif expr.has_key('alternate'):
748 check_alternate(expr, info)
749 elif expr.has_key('struct'):
750 check_struct(expr, info)
751 elif expr.has_key('command'):
752 check_command(expr, info)
753 elif expr.has_key('event'):
754 check_event(expr, info)
755 else:
756 assert False, 'unexpected meta type'
757
758 return map(lambda expr_elem: expr_elem['expr'], exprs)
Eric Blake0545f6b2015-05-04 09:05:15 -0600759
Markus Armbruster54414042015-06-09 16:22:45 +0200760def parse_schema(fname):
Markus Armbruster2caba362013-07-27 17:41:56 +0200761 try:
Markus Armbruster54414042015-06-09 16:22:45 +0200762 schema = QAPISchema(open(fname, "r"))
Markus Armbruster4d076d62015-06-10 08:55:21 +0200763 return check_exprs(schema.exprs)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200764 except (QAPISchemaError, QAPIExprError), e:
Markus Armbruster2caba362013-07-27 17:41:56 +0200765 print >>sys.stderr, e
766 exit(1)
767
Markus Armbruster00e4b282015-06-10 10:04:36 +0200768#
769# Code generation helpers
770#
771
Michael Roth0f923be2011-07-19 14:50:39 -0500772def parse_args(typeinfo):
Eric Blakefe2a9302015-05-04 09:05:02 -0600773 if isinstance(typeinfo, str):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200774 struct = find_struct(typeinfo)
775 assert struct != None
776 typeinfo = struct['data']
777
Michael Roth0f923be2011-07-19 14:50:39 -0500778 for member in typeinfo:
779 argname = member
780 argentry = typeinfo[member]
781 optional = False
Michael Roth0f923be2011-07-19 14:50:39 -0500782 if member.startswith('*'):
783 argname = member[1:]
784 optional = True
Eric Blake6b5abc72015-05-04 09:05:33 -0600785 # Todo: allow argentry to be OrderedDict, for providing the
786 # value of an optional argument.
787 yield (argname, argentry, optional)
Michael Roth0f923be2011-07-19 14:50:39 -0500788
Michael Roth0f923be2011-07-19 14:50:39 -0500789def camel_case(name):
790 new_name = ''
791 first = True
792 for ch in name:
793 if ch in ['_', '-']:
794 first = True
795 elif first:
796 new_name += ch.upper()
797 first = False
798 else:
799 new_name += ch.lower()
800 return new_name
801
Markus Armbruster849bc532015-05-14 06:50:53 -0600802# ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
803# ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
804# ENUM24_Name -> ENUM24_NAME
805def camel_to_upper(value):
806 c_fun_str = c_name(value, False)
807 if value.isupper():
808 return c_fun_str
809
810 new_name = ''
811 l = len(c_fun_str)
812 for i in range(l):
813 c = c_fun_str[i]
814 # When c is upper and no "_" appears before, do more checks
815 if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
816 # Case 1: next string is lower
817 # Case 2: previous string is digit
818 if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
819 c_fun_str[i - 1].isdigit():
820 new_name += '_'
821 new_name += c
822 return new_name.lstrip('_').upper()
823
824def c_enum_const(type_name, const_name):
825 return camel_to_upper(type_name + '_' + const_name)
826
Eric Blake18df5152015-05-14 06:50:48 -0600827c_name_trans = string.maketrans('.-', '__')
Markus Armbruster47299262015-05-14 06:50:47 -0600828
Eric Blakec6405b52015-05-14 06:50:55 -0600829# Map @name to a valid C identifier.
830# If @protect, avoid returning certain ticklish identifiers (like
831# C keywords) by prepending "q_".
832#
833# Used for converting 'name' from a 'name':'type' qapi definition
834# into a generated struct member, as well as converting type names
835# into substrings of a generated C function name.
836# '__a.b_c' -> '__a_b_c', 'x-foo' -> 'x_foo'
837# protect=True: 'int' -> 'q_int'; protect=False: 'int' -> 'int'
Eric Blake18df5152015-05-14 06:50:48 -0600838def c_name(name, protect=True):
Blue Swirl427a1a22012-07-30 15:46:55 +0000839 # ANSI X3J11/88-090, 3.1.1
840 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
841 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
842 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
843 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
844 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
845 # ISO/IEC 9899:1999, 6.4.1
846 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
847 # ISO/IEC 9899:2011, 6.4.1
848 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
849 '_Static_assert', '_Thread_local'])
850 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
851 # excluding _.*
852 gcc_words = set(['asm', 'typeof'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400853 # C++ ISO/IEC 14882:2003 2.11
854 cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
855 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
856 'namespace', 'new', 'operator', 'private', 'protected',
857 'public', 'reinterpret_cast', 'static_cast', 'template',
858 'this', 'throw', 'true', 'try', 'typeid', 'typename',
859 'using', 'virtual', 'wchar_t',
860 # alternative representations
861 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
862 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
Paolo Bonzini10577252012-09-19 16:31:07 +0200863 # namespace pollution:
Max Reitz8592a542013-12-20 19:28:18 +0100864 polluted_words = set(['unix', 'errno'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400865 if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
Blue Swirl427a1a22012-07-30 15:46:55 +0000866 return "q_" + name
Eric Blake18df5152015-05-14 06:50:48 -0600867 return name.translate(c_name_trans)
Michael Roth0f923be2011-07-19 14:50:39 -0500868
Eric Blakec6405b52015-05-14 06:50:55 -0600869# Map type @name to the C typedef name for the list form.
870#
871# ['Name'] -> 'NameList', ['x-Foo'] -> 'x_FooList', ['int'] -> 'intList'
Michael Roth0f923be2011-07-19 14:50:39 -0500872def c_list_type(name):
Eric Blakec6405b52015-05-14 06:50:55 -0600873 return type_name(name) + 'List'
Michael Roth0f923be2011-07-19 14:50:39 -0500874
Eric Blakec6405b52015-05-14 06:50:55 -0600875# Map type @value to the C typedef form.
876#
877# Used for converting 'type' from a 'member':'type' qapi definition
878# into the alphanumeric portion of the type for a generated C parameter,
879# as well as generated C function names. See c_type() for the rest of
880# the conversion such as adding '*' on pointer types.
881# 'int' -> 'int', '[x-Foo]' -> 'x_FooList', '__a.b_c' -> '__a_b_c'
Eric Blaked5573442015-05-14 06:50:54 -0600882def type_name(value):
883 if type(value) == list:
884 return c_list_type(value[0])
Eric Blakec6405b52015-05-14 06:50:55 -0600885 if value in builtin_types.keys():
886 return value
887 return c_name(value)
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
Markus Armbruster77e703b2015-06-24 19:27:32 +0200949# Generate @code with @kwds interpolated.
950# Obey indent_level, and strip eatspace.
Michael Roth0f923be2011-07-19 14:50:39 -0500951def cgen(code, **kwds):
Markus Armbruster77e703b2015-06-24 19:27:32 +0200952 raw = code % kwds
953 if indent_level:
954 indent = genindent(indent_level)
955 raw = re.subn("^.", indent + r'\g<0>', raw, 0, re.MULTILINE)
956 raw = raw[0]
957 return re.sub(re.escape(eatspace) + ' *', '', raw)
Michael Roth0f923be2011-07-19 14:50:39 -0500958
959def mcgen(code, **kwds):
Markus Armbruster77e703b2015-06-24 19:27:32 +0200960 if code[0] == '\n':
961 code = code[1:]
962 return cgen(code, **kwds)
Michael Roth0f923be2011-07-19 14:50:39 -0500963
Michael Roth0f923be2011-07-19 14:50:39 -0500964
965def guardname(filename):
Markus Armbruster00dfc3b2015-06-27 07:27:21 +0200966 return c_name(filename, protect=False).upper()
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
Markus Armbruster00e4b282015-06-10 10:04:36 +0200985#
986# Common command line parsing
987#
988
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200989def parse_command_line(extra_options = "", extra_long_options = []):
990
991 try:
992 opts, args = getopt.gnu_getopt(sys.argv[1:],
Markus Armbruster16d80f62015-04-02 13:32:16 +0200993 "chp:o:" + extra_options,
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200994 ["source", "header", "prefix=",
Markus Armbruster16d80f62015-04-02 13:32:16 +0200995 "output-dir="] + extra_long_options)
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200996 except getopt.GetoptError, err:
Markus Armbrusterb4540962015-04-02 13:17:34 +0200997 print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
Markus Armbruster2114f5a2015-04-02 13:12:21 +0200998 sys.exit(1)
999
1000 output_dir = ""
1001 prefix = ""
1002 do_c = False
1003 do_h = False
1004 extra_opts = []
1005
1006 for oa in opts:
1007 o, a = oa
1008 if o in ("-p", "--prefix"):
Markus Armbruster1cf47a12015-07-01 13:13:54 +02001009 match = re.match('([A-Za-z_.-][A-Za-z0-9_.-]*)?', a)
1010 if match.end() != len(a):
1011 print >>sys.stderr, \
1012 "%s: 'funny character '%s' in argument of --prefix" \
1013 % (sys.argv[0], a[match.end()])
1014 sys.exit(1)
Markus Armbruster2114f5a2015-04-02 13:12:21 +02001015 prefix = a
Markus Armbruster2114f5a2015-04-02 13:12:21 +02001016 elif o in ("-o", "--output-dir"):
1017 output_dir = a + "/"
1018 elif o in ("-c", "--source"):
1019 do_c = True
1020 elif o in ("-h", "--header"):
1021 do_h = True
1022 else:
1023 extra_opts.append(oa)
1024
1025 if not do_c and not do_h:
1026 do_c = True
1027 do_h = True
1028
Markus Armbruster16d80f62015-04-02 13:32:16 +02001029 if len(args) != 1:
1030 print >>sys.stderr, "%s: need exactly one argument" % sys.argv[0]
Markus Armbrusterb4540962015-04-02 13:17:34 +02001031 sys.exit(1)
Markus Armbruster54414042015-06-09 16:22:45 +02001032 fname = args[0]
Markus Armbrusterb4540962015-04-02 13:17:34 +02001033
Markus Armbruster54414042015-06-09 16:22:45 +02001034 return (fname, output_dir, do_c, do_h, prefix, extra_opts)
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001035
Markus Armbruster00e4b282015-06-10 10:04:36 +02001036#
1037# Generate output files with boilerplate
1038#
1039
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001040def open_output(output_dir, do_c, do_h, prefix, c_file, h_file,
1041 c_comment, h_comment):
Markus Armbruster00dfc3b2015-06-27 07:27:21 +02001042 guard = guardname(prefix + h_file)
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001043 c_file = output_dir + prefix + c_file
1044 h_file = output_dir + prefix + h_file
1045
1046 try:
1047 os.makedirs(output_dir)
1048 except os.error, e:
1049 if e.errno != errno.EEXIST:
1050 raise
1051
1052 def maybe_open(really, name, opt):
1053 if really:
1054 return open(name, opt)
1055 else:
1056 import StringIO
1057 return StringIO.StringIO()
1058
1059 fdef = maybe_open(do_c, c_file, 'w')
1060 fdecl = maybe_open(do_h, h_file, 'w')
1061
1062 fdef.write(mcgen('''
1063/* AUTOMATICALLY GENERATED, DO NOT MODIFY */
1064%(comment)s
1065''',
1066 comment = c_comment))
1067
1068 fdecl.write(mcgen('''
1069/* AUTOMATICALLY GENERATED, DO NOT MODIFY */
1070%(comment)s
1071#ifndef %(guard)s
1072#define %(guard)s
1073
1074''',
Markus Armbruster00dfc3b2015-06-27 07:27:21 +02001075 comment = h_comment, guard = guard))
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001076
1077 return (fdef, fdecl)
1078
1079def close_output(fdef, fdecl):
1080 fdecl.write('''
1081#endif
1082''')
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001083 fdecl.close()
Markus Armbruster12f8e1b2015-04-02 14:46:39 +02001084 fdef.close()