qapi: Tidy c_type() logic
[qemu.git] / scripts / qapi.py
blobecab87907c018d99657c17b33df0d5b3b7b0863d
2 # QAPI helper library
4 # Copyright IBM, Corp. 2011
5 # Copyright (c) 2013-2015 Red Hat Inc.
7 # Authors:
8 # Anthony Liguori <aliguori@us.ibm.com>
9 # Markus Armbruster <armbru@redhat.com>
11 # This work is licensed under the terms of the GNU GPL, version 2.
12 # See the COPYING file in the top-level directory.
14 import re
15 from ordereddict import OrderedDict
16 import os
17 import sys
18 import string
20 builtin_types = {
21 'str': 'QTYPE_QSTRING',
22 'int': 'QTYPE_QINT',
23 'number': 'QTYPE_QFLOAT',
24 'bool': 'QTYPE_QBOOL',
25 'int8': 'QTYPE_QINT',
26 'int16': 'QTYPE_QINT',
27 'int32': 'QTYPE_QINT',
28 'int64': 'QTYPE_QINT',
29 'uint8': 'QTYPE_QINT',
30 'uint16': 'QTYPE_QINT',
31 'uint32': 'QTYPE_QINT',
32 'uint64': 'QTYPE_QINT',
33 'size': 'QTYPE_QINT',
36 # Whitelist of commands allowed to return a non-dictionary
37 returns_whitelist = [
38 # From QMP:
39 'human-monitor-command',
40 'query-migrate-cache-size',
41 'query-tpm-models',
42 'query-tpm-types',
43 'ringbuf-read',
45 # From QGA:
46 'guest-file-open',
47 'guest-fsfreeze-freeze',
48 'guest-fsfreeze-freeze-list',
49 'guest-fsfreeze-status',
50 'guest-fsfreeze-thaw',
51 'guest-get-time',
52 'guest-set-vcpus',
53 'guest-sync',
54 'guest-sync-delimited',
56 # From qapi-schema-test:
57 'user_def_cmd3',
60 enum_types = []
61 struct_types = []
62 union_types = []
63 events = []
64 all_names = {}
66 def error_path(parent):
67 res = ""
68 while parent:
69 res = ("In file included from %s:%d:\n" % (parent['file'],
70 parent['line'])) + res
71 parent = parent['parent']
72 return res
74 class QAPISchemaError(Exception):
75 def __init__(self, schema, msg):
76 self.input_file = schema.input_file
77 self.msg = msg
78 self.col = 1
79 self.line = schema.line
80 for ch in schema.src[schema.line_pos:schema.pos]:
81 if ch == '\t':
82 self.col = (self.col + 7) % 8 + 1
83 else:
84 self.col += 1
85 self.info = schema.parent_info
87 def __str__(self):
88 return error_path(self.info) + \
89 "%s:%d:%d: %s" % (self.input_file, self.line, self.col, self.msg)
91 class QAPIExprError(Exception):
92 def __init__(self, expr_info, msg):
93 self.info = expr_info
94 self.msg = msg
96 def __str__(self):
97 return error_path(self.info['parent']) + \
98 "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
100 class QAPISchema:
102 def __init__(self, fp, input_relname=None, include_hist=[],
103 previously_included=[], parent_info=None):
104 """ include_hist is a stack used to detect inclusion cycles
105 previously_included is a global state used to avoid multiple
106 inclusions of the same file"""
107 input_fname = os.path.abspath(fp.name)
108 if input_relname is None:
109 input_relname = fp.name
110 self.input_dir = os.path.dirname(input_fname)
111 self.input_file = input_relname
112 self.include_hist = include_hist + [(input_relname, input_fname)]
113 previously_included.append(input_fname)
114 self.parent_info = parent_info
115 self.src = fp.read()
116 if self.src == '' or self.src[-1] != '\n':
117 self.src += '\n'
118 self.cursor = 0
119 self.line = 1
120 self.line_pos = 0
121 self.exprs = []
122 self.accept()
124 while self.tok != None:
125 expr_info = {'file': input_relname, 'line': self.line, 'parent': self.parent_info}
126 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)
135 include_path = os.path.join(self.input_dir, include)
136 for elem in self.include_hist:
137 if include_path == elem[1]:
138 raise QAPIExprError(expr_info, "Inclusion loop for %s"
139 % include)
140 # skip multiple include of the same file
141 if include_path in previously_included:
142 continue
143 try:
144 fobj = open(include_path, 'r')
145 except IOError, e:
146 raise QAPIExprError(expr_info,
147 '%s: %s' % (e.strerror, include))
148 exprs_include = QAPISchema(fobj, include, self.include_hist,
149 previously_included, expr_info)
150 self.exprs.extend(exprs_include.exprs)
151 else:
152 expr_elem = {'expr': expr,
153 'info': expr_info}
154 self.exprs.append(expr_elem)
156 def accept(self):
157 while True:
158 self.tok = self.src[self.cursor]
159 self.pos = self.cursor
160 self.cursor += 1
161 self.val = None
163 if self.tok == '#':
164 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':
174 raise QAPISchemaError(self,
175 'Missing terminating "\'"')
176 if esc:
177 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)
212 esc = False
213 elif ch == "\\":
214 esc = True
215 elif ch == "'":
216 self.val = string
217 return
218 else:
219 string += ch
220 elif self.tok in "tfn":
221 val = self.src[self.cursor - 1:]
222 if val.startswith("true"):
223 self.val = True
224 self.cursor += 3
225 return
226 elif val.startswith("false"):
227 self.val = False
228 self.cursor += 4
229 return
230 elif val.startswith("null"):
231 self.val = None
232 self.cursor += 3
233 return
234 elif self.tok == '\n':
235 if self.cursor == len(self.src):
236 self.tok = None
237 return
238 self.line += 1
239 self.line_pos = self.cursor
240 elif not self.tok.isspace():
241 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
243 def get_members(self):
244 expr = OrderedDict()
245 if self.tok == '}':
246 self.accept()
247 return expr
248 if self.tok != "'":
249 raise QAPISchemaError(self, 'Expected string or "}"')
250 while True:
251 key = self.val
252 self.accept()
253 if self.tok != ':':
254 raise QAPISchemaError(self, 'Expected ":"')
255 self.accept()
256 if key in expr:
257 raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
258 expr[key] = self.get_expr(True)
259 if self.tok == '}':
260 self.accept()
261 return expr
262 if self.tok != ',':
263 raise QAPISchemaError(self, 'Expected "," or "}"')
264 self.accept()
265 if self.tok != "'":
266 raise QAPISchemaError(self, 'Expected string')
268 def get_values(self):
269 expr = []
270 if self.tok == ']':
271 self.accept()
272 return expr
273 if not self.tok in "{['tfn":
274 raise QAPISchemaError(self, 'Expected "{", "[", "]", string, '
275 'boolean or "null"')
276 while True:
277 expr.append(self.get_expr(True))
278 if self.tok == ']':
279 self.accept()
280 return expr
281 if self.tok != ',':
282 raise QAPISchemaError(self, 'Expected "," or "]"')
283 self.accept()
285 def get_expr(self, nested):
286 if self.tok != '{' and not nested:
287 raise QAPISchemaError(self, 'Expected "{"')
288 if self.tok == '{':
289 self.accept()
290 expr = self.get_members()
291 elif self.tok == '[':
292 self.accept()
293 expr = self.get_values()
294 elif self.tok in "'tfn":
295 expr = self.val
296 self.accept()
297 else:
298 raise QAPISchemaError(self, 'Expected "{", "[" or string')
299 return expr
301 def find_base_fields(base):
302 base_struct_define = find_struct(base)
303 if not base_struct_define:
304 return None
305 return base_struct_define['data']
307 # Return the qtype of an alternate branch, or None on error.
308 def find_alternate_member_qtype(qapi_type):
309 if builtin_types.has_key(qapi_type):
310 return builtin_types[qapi_type]
311 elif find_struct(qapi_type):
312 return "QTYPE_QDICT"
313 elif find_enum(qapi_type):
314 return "QTYPE_QSTRING"
315 elif find_union(qapi_type):
316 return "QTYPE_QDICT"
317 return None
319 # Return the discriminator enum define if discriminator is specified as an
320 # enum type, otherwise return None.
321 def discriminator_find_enum_define(expr):
322 base = expr.get('base')
323 discriminator = expr.get('discriminator')
325 if not (discriminator and base):
326 return None
328 base_fields = find_base_fields(base)
329 if not base_fields:
330 return None
332 discriminator_type = base_fields.get(discriminator)
333 if not discriminator_type:
334 return None
336 return find_enum(discriminator_type)
338 valid_name = re.compile('^[a-zA-Z_][a-zA-Z0-9_.-]*$')
339 def check_name(expr_info, source, name, allow_optional = False,
340 enum_member = False):
341 global valid_name
342 membername = name
344 if not isinstance(name, str):
345 raise QAPIExprError(expr_info,
346 "%s requires a string name" % source)
347 if name.startswith('*'):
348 membername = name[1:]
349 if not allow_optional:
350 raise QAPIExprError(expr_info,
351 "%s does not allow optional name '%s'"
352 % (source, name))
353 # Enum members can start with a digit, because the generated C
354 # code always prefixes it with the enum name
355 if enum_member:
356 membername = '_' + membername
357 if not valid_name.match(membername):
358 raise QAPIExprError(expr_info,
359 "%s uses invalid name '%s'" % (source, name))
361 def check_type(expr_info, source, value, allow_array = False,
362 allow_dict = False, allow_optional = False,
363 allow_star = False, allow_metas = []):
364 global all_names
365 orig_value = value
367 if value is None:
368 return
370 if allow_star and value == '**':
371 return
373 # Check if array type for value is okay
374 if isinstance(value, list):
375 if not allow_array:
376 raise QAPIExprError(expr_info,
377 "%s cannot be an array" % source)
378 if len(value) != 1 or not isinstance(value[0], str):
379 raise QAPIExprError(expr_info,
380 "%s: array type must contain single type name"
381 % source)
382 value = value[0]
383 orig_value = "array of %s" %value
385 # Check if type name for value is okay
386 if isinstance(value, str):
387 if value == '**':
388 raise QAPIExprError(expr_info,
389 "%s uses '**' but did not request 'gen':false"
390 % source)
391 if not value in all_names:
392 raise QAPIExprError(expr_info,
393 "%s uses unknown type '%s'"
394 % (source, orig_value))
395 if not all_names[value] in allow_metas:
396 raise QAPIExprError(expr_info,
397 "%s cannot use %s type '%s'"
398 % (source, all_names[value], orig_value))
399 return
401 # value is a dictionary, check that each member is okay
402 if not isinstance(value, OrderedDict):
403 raise QAPIExprError(expr_info,
404 "%s should be a dictionary" % source)
405 if not allow_dict:
406 raise QAPIExprError(expr_info,
407 "%s should be a type name" % source)
408 for (key, arg) in value.items():
409 check_name(expr_info, "Member of %s" % source, key,
410 allow_optional=allow_optional)
411 # Todo: allow dictionaries to represent default values of
412 # an optional argument.
413 check_type(expr_info, "Member '%s' of %s" % (key, source), arg,
414 allow_array=True, allow_star=allow_star,
415 allow_metas=['built-in', 'union', 'alternate', 'struct',
416 'enum'])
418 def check_member_clash(expr_info, base_name, data, source = ""):
419 base = find_struct(base_name)
420 assert base
421 base_members = base['data']
422 for key in data.keys():
423 if key.startswith('*'):
424 key = key[1:]
425 if key in base_members or "*" + key in base_members:
426 raise QAPIExprError(expr_info,
427 "Member name '%s'%s clashes with base '%s'"
428 % (key, source, base_name))
429 if base.get('base'):
430 check_member_clash(expr_info, base['base'], data, source)
432 def check_command(expr, expr_info):
433 name = expr['command']
434 allow_star = expr.has_key('gen')
436 check_type(expr_info, "'data' for command '%s'" % name,
437 expr.get('data'), allow_dict=True, allow_optional=True,
438 allow_metas=['union', 'struct'], allow_star=allow_star)
439 returns_meta = ['union', 'struct']
440 if name in returns_whitelist:
441 returns_meta += ['built-in', 'alternate', 'enum']
442 check_type(expr_info, "'returns' for command '%s'" % name,
443 expr.get('returns'), allow_array=True, allow_dict=True,
444 allow_optional=True, allow_metas=returns_meta,
445 allow_star=allow_star)
447 def check_event(expr, expr_info):
448 global events
449 name = expr['event']
450 params = expr.get('data')
452 if name.upper() == 'MAX':
453 raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created")
454 events.append(name)
455 check_type(expr_info, "'data' for event '%s'" % name,
456 expr.get('data'), allow_dict=True, allow_optional=True,
457 allow_metas=['union', 'struct'])
459 def check_union(expr, expr_info):
460 name = expr['union']
461 base = expr.get('base')
462 discriminator = expr.get('discriminator')
463 members = expr['data']
464 values = { 'MAX': '(automatic)' }
466 # If the object has a member 'base', its value must name a struct,
467 # and there must be a discriminator.
468 if base is not None:
469 if discriminator is None:
470 raise QAPIExprError(expr_info,
471 "Union '%s' requires a discriminator to go "
472 "along with base" %name)
474 # Two types of unions, determined by discriminator.
476 # With no discriminator it is a simple union.
477 if discriminator is None:
478 enum_define = None
479 allow_metas=['built-in', 'union', 'alternate', 'struct', 'enum']
480 if base is not None:
481 raise QAPIExprError(expr_info,
482 "Simple union '%s' must not have a base"
483 % name)
485 # Else, it's a flat union.
486 else:
487 # The object must have a string member 'base'.
488 if not isinstance(base, str):
489 raise QAPIExprError(expr_info,
490 "Flat union '%s' must have a string base field"
491 % name)
492 base_fields = find_base_fields(base)
493 if not base_fields:
494 raise QAPIExprError(expr_info,
495 "Base '%s' is not a valid struct"
496 % base)
498 # The value of member 'discriminator' must name a non-optional
499 # member of the base struct.
500 check_name(expr_info, "Discriminator of flat union '%s'" % name,
501 discriminator)
502 discriminator_type = base_fields.get(discriminator)
503 if not discriminator_type:
504 raise QAPIExprError(expr_info,
505 "Discriminator '%s' is not a member of base "
506 "struct '%s'"
507 % (discriminator, base))
508 enum_define = find_enum(discriminator_type)
509 allow_metas=['struct']
510 # Do not allow string discriminator
511 if not enum_define:
512 raise QAPIExprError(expr_info,
513 "Discriminator '%s' must be of enumeration "
514 "type" % discriminator)
516 # Check every branch
517 for (key, value) in members.items():
518 check_name(expr_info, "Member of union '%s'" % name, key)
520 # Each value must name a known type; furthermore, in flat unions,
521 # branches must be a struct with no overlapping member names
522 check_type(expr_info, "Member '%s' of union '%s'" % (key, name),
523 value, allow_array=True, allow_metas=allow_metas)
524 if base:
525 branch_struct = find_struct(value)
526 assert branch_struct
527 check_member_clash(expr_info, base, branch_struct['data'],
528 " of branch '%s'" % key)
530 # If the discriminator names an enum type, then all members
531 # of 'data' must also be members of the enum type.
532 if enum_define:
533 if not key in enum_define['enum_values']:
534 raise QAPIExprError(expr_info,
535 "Discriminator value '%s' is not found in "
536 "enum '%s'" %
537 (key, enum_define["enum_name"]))
539 # Otherwise, check for conflicts in the generated enum
540 else:
541 c_key = camel_to_upper(key)
542 if c_key in values:
543 raise QAPIExprError(expr_info,
544 "Union '%s' member '%s' clashes with '%s'"
545 % (name, key, values[c_key]))
546 values[c_key] = key
548 def check_alternate(expr, expr_info):
549 name = expr['alternate']
550 members = expr['data']
551 values = { 'MAX': '(automatic)' }
552 types_seen = {}
554 # Check every branch
555 for (key, value) in members.items():
556 check_name(expr_info, "Member of alternate '%s'" % name, key)
558 # Check for conflicts in the generated enum
559 c_key = camel_to_upper(key)
560 if c_key in values:
561 raise QAPIExprError(expr_info,
562 "Alternate '%s' member '%s' clashes with '%s'"
563 % (name, key, values[c_key]))
564 values[c_key] = key
566 # Ensure alternates have no type conflicts.
567 check_type(expr_info, "Member '%s' of alternate '%s'" % (key, name),
568 value,
569 allow_metas=['built-in', 'union', 'struct', 'enum'])
570 qtype = find_alternate_member_qtype(value)
571 assert qtype
572 if qtype in types_seen:
573 raise QAPIExprError(expr_info,
574 "Alternate '%s' member '%s' can't "
575 "be distinguished from member '%s'"
576 % (name, key, types_seen[qtype]))
577 types_seen[qtype] = key
579 def check_enum(expr, expr_info):
580 name = expr['enum']
581 members = expr.get('data')
582 values = { 'MAX': '(automatic)' }
584 if not isinstance(members, list):
585 raise QAPIExprError(expr_info,
586 "Enum '%s' requires an array for 'data'" % name)
587 for member in members:
588 check_name(expr_info, "Member of enum '%s'" %name, member,
589 enum_member=True)
590 key = camel_to_upper(member)
591 if key in values:
592 raise QAPIExprError(expr_info,
593 "Enum '%s' member '%s' clashes with '%s'"
594 % (name, member, values[key]))
595 values[key] = member
597 def check_struct(expr, expr_info):
598 name = expr['struct']
599 members = expr['data']
601 check_type(expr_info, "'data' for struct '%s'" % name, members,
602 allow_dict=True, allow_optional=True)
603 check_type(expr_info, "'base' for struct '%s'" % name, expr.get('base'),
604 allow_metas=['struct'])
605 if expr.get('base'):
606 check_member_clash(expr_info, expr['base'], expr['data'])
608 def check_exprs(schema):
609 for expr_elem in schema.exprs:
610 expr = expr_elem['expr']
611 info = expr_elem['info']
613 if expr.has_key('enum'):
614 check_enum(expr, info)
615 elif expr.has_key('union'):
616 check_union(expr, info)
617 elif expr.has_key('alternate'):
618 check_alternate(expr, info)
619 elif expr.has_key('struct'):
620 check_struct(expr, info)
621 elif expr.has_key('command'):
622 check_command(expr, info)
623 elif expr.has_key('event'):
624 check_event(expr, info)
625 else:
626 assert False, 'unexpected meta type'
628 def check_keys(expr_elem, meta, required, optional=[]):
629 expr = expr_elem['expr']
630 info = expr_elem['info']
631 name = expr[meta]
632 if not isinstance(name, str):
633 raise QAPIExprError(info,
634 "'%s' key must have a string value" % meta)
635 required = required + [ meta ]
636 for (key, value) in expr.items():
637 if not key in required and not key in optional:
638 raise QAPIExprError(info,
639 "Unknown key '%s' in %s '%s'"
640 % (key, meta, name))
641 if (key == 'gen' or key == 'success-response') and value != False:
642 raise QAPIExprError(info,
643 "'%s' of %s '%s' should only use false value"
644 % (key, meta, name))
645 for key in required:
646 if not expr.has_key(key):
647 raise QAPIExprError(info,
648 "Key '%s' is missing from %s '%s'"
649 % (key, meta, name))
652 def parse_schema(input_file):
653 global all_names
654 exprs = []
656 # First pass: read entire file into memory
657 try:
658 schema = QAPISchema(open(input_file, "r"))
659 except (QAPISchemaError, QAPIExprError), e:
660 print >>sys.stderr, e
661 exit(1)
663 try:
664 # Next pass: learn the types and check for valid expression keys. At
665 # this point, top-level 'include' has already been flattened.
666 for builtin in builtin_types.keys():
667 all_names[builtin] = 'built-in'
668 for expr_elem in schema.exprs:
669 expr = expr_elem['expr']
670 info = expr_elem['info']
671 if expr.has_key('enum'):
672 check_keys(expr_elem, 'enum', ['data'])
673 add_enum(expr['enum'], info, expr['data'])
674 elif expr.has_key('union'):
675 check_keys(expr_elem, 'union', ['data'],
676 ['base', 'discriminator'])
677 add_union(expr, info)
678 elif expr.has_key('alternate'):
679 check_keys(expr_elem, 'alternate', ['data'])
680 add_name(expr['alternate'], info, 'alternate')
681 elif expr.has_key('struct'):
682 check_keys(expr_elem, 'struct', ['data'], ['base'])
683 add_struct(expr, info)
684 elif expr.has_key('command'):
685 check_keys(expr_elem, 'command', [],
686 ['data', 'returns', 'gen', 'success-response'])
687 add_name(expr['command'], info, 'command')
688 elif expr.has_key('event'):
689 check_keys(expr_elem, 'event', [], ['data'])
690 add_name(expr['event'], info, 'event')
691 else:
692 raise QAPIExprError(expr_elem['info'],
693 "Expression is missing metatype")
694 exprs.append(expr)
696 # Try again for hidden UnionKind enum
697 for expr_elem in schema.exprs:
698 expr = expr_elem['expr']
699 if expr.has_key('union'):
700 if not discriminator_find_enum_define(expr):
701 add_enum('%sKind' % expr['union'], expr_elem['info'],
702 implicit=True)
703 elif expr.has_key('alternate'):
704 add_enum('%sKind' % expr['alternate'], expr_elem['info'],
705 implicit=True)
707 # Final pass - validate that exprs make sense
708 check_exprs(schema)
709 except QAPIExprError, e:
710 print >>sys.stderr, e
711 exit(1)
713 return exprs
715 def parse_args(typeinfo):
716 if isinstance(typeinfo, str):
717 struct = find_struct(typeinfo)
718 assert struct != None
719 typeinfo = struct['data']
721 for member in typeinfo:
722 argname = member
723 argentry = typeinfo[member]
724 optional = False
725 if member.startswith('*'):
726 argname = member[1:]
727 optional = True
728 # Todo: allow argentry to be OrderedDict, for providing the
729 # value of an optional argument.
730 yield (argname, argentry, optional)
732 def camel_case(name):
733 new_name = ''
734 first = True
735 for ch in name:
736 if ch in ['_', '-']:
737 first = True
738 elif first:
739 new_name += ch.upper()
740 first = False
741 else:
742 new_name += ch.lower()
743 return new_name
745 # ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
746 # ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
747 # ENUM24_Name -> ENUM24_NAME
748 def camel_to_upper(value):
749 c_fun_str = c_name(value, False)
750 if value.isupper():
751 return c_fun_str
753 new_name = ''
754 l = len(c_fun_str)
755 for i in range(l):
756 c = c_fun_str[i]
757 # When c is upper and no "_" appears before, do more checks
758 if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
759 # Case 1: next string is lower
760 # Case 2: previous string is digit
761 if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
762 c_fun_str[i - 1].isdigit():
763 new_name += '_'
764 new_name += c
765 return new_name.lstrip('_').upper()
767 def c_enum_const(type_name, const_name):
768 return camel_to_upper(type_name + '_' + const_name)
770 c_name_trans = string.maketrans('.-', '__')
772 def c_name(name, protect=True):
773 # ANSI X3J11/88-090, 3.1.1
774 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
775 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
776 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
777 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
778 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
779 # ISO/IEC 9899:1999, 6.4.1
780 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
781 # ISO/IEC 9899:2011, 6.4.1
782 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
783 '_Static_assert', '_Thread_local'])
784 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
785 # excluding _.*
786 gcc_words = set(['asm', 'typeof'])
787 # C++ ISO/IEC 14882:2003 2.11
788 cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
789 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
790 'namespace', 'new', 'operator', 'private', 'protected',
791 'public', 'reinterpret_cast', 'static_cast', 'template',
792 'this', 'throw', 'true', 'try', 'typeid', 'typename',
793 'using', 'virtual', 'wchar_t',
794 # alternative representations
795 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
796 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
797 # namespace pollution:
798 polluted_words = set(['unix', 'errno'])
799 if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
800 return "q_" + name
801 return name.translate(c_name_trans)
803 def c_list_type(name):
804 return name + 'List'
806 def type_name(value):
807 if type(value) == list:
808 return c_list_type(value[0])
809 return value
811 def add_name(name, info, meta, implicit = False):
812 global all_names
813 check_name(info, "'%s'" % meta, name)
814 if name in all_names:
815 raise QAPIExprError(info,
816 "%s '%s' is already defined"
817 % (all_names[name], name))
818 if not implicit and name[-4:] == 'Kind':
819 raise QAPIExprError(info,
820 "%s '%s' should not end in 'Kind'"
821 % (meta, name))
822 all_names[name] = meta
824 def add_struct(definition, info):
825 global struct_types
826 name = definition['struct']
827 add_name(name, info, 'struct')
828 struct_types.append(definition)
830 def find_struct(name):
831 global struct_types
832 for struct in struct_types:
833 if struct['struct'] == name:
834 return struct
835 return None
837 def add_union(definition, info):
838 global union_types
839 name = definition['union']
840 add_name(name, info, 'union')
841 union_types.append(definition)
843 def find_union(name):
844 global union_types
845 for union in union_types:
846 if union['union'] == name:
847 return union
848 return None
850 def add_enum(name, info, enum_values = None, implicit = False):
851 global enum_types
852 add_name(name, info, 'enum', implicit)
853 enum_types.append({"enum_name": name, "enum_values": enum_values})
855 def find_enum(name):
856 global enum_types
857 for enum in enum_types:
858 if enum['enum_name'] == name:
859 return enum
860 return None
862 def is_enum(name):
863 return find_enum(name) != None
865 eatspace = '\033EATSPACE.'
866 pointer_suffix = ' *' + eatspace
868 # A special suffix is added in c_type() for pointer types, and it's
869 # stripped in mcgen(). So please notice this when you check the return
870 # value of c_type() outside mcgen().
871 def c_type(value, is_param=False):
872 if value == 'str':
873 if is_param:
874 return 'const char' + pointer_suffix
875 return 'char' + pointer_suffix
877 elif value == 'int':
878 return 'int64_t'
879 elif (value == 'int8' or value == 'int16' or value == 'int32' or
880 value == 'int64' or value == 'uint8' or value == 'uint16' or
881 value == 'uint32' or value == 'uint64'):
882 return value + '_t'
883 elif value == 'size':
884 return 'uint64_t'
885 elif value == 'bool':
886 return 'bool'
887 elif value == 'number':
888 return 'double'
889 elif type(value) == list:
890 return c_list_type(value[0]) + pointer_suffix
891 elif is_enum(value):
892 return value
893 elif value == None:
894 return 'void'
895 elif value in events:
896 return camel_case(value) + 'Event' + pointer_suffix
897 else:
898 # complex type name
899 assert isinstance(value, str) and value != ""
900 return value + pointer_suffix
902 def is_c_ptr(value):
903 return c_type(value).endswith(pointer_suffix)
905 def genindent(count):
906 ret = ""
907 for i in range(count):
908 ret += " "
909 return ret
911 indent_level = 0
913 def push_indent(indent_amount=4):
914 global indent_level
915 indent_level += indent_amount
917 def pop_indent(indent_amount=4):
918 global indent_level
919 indent_level -= indent_amount
921 def cgen(code, **kwds):
922 indent = genindent(indent_level)
923 lines = code.split('\n')
924 lines = map(lambda x: indent + x, lines)
925 return '\n'.join(lines) % kwds + '\n'
927 def mcgen(code, **kwds):
928 raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
929 return re.sub(re.escape(eatspace) + ' *', '', raw)
931 def basename(filename):
932 return filename.split("/")[-1]
934 def guardname(filename):
935 guard = basename(filename).rsplit(".", 1)[0]
936 for substr in [".", " ", "-"]:
937 guard = guard.replace(substr, "_")
938 return guard.upper() + '_H'
940 def guardstart(name):
941 return mcgen('''
943 #ifndef %(name)s
944 #define %(name)s
946 ''',
947 name=guardname(name))
949 def guardend(name):
950 return mcgen('''
952 #endif /* %(name)s */
954 ''',
955 name=guardname(name))