qapi: Rename _generate_enum_string() to camel_to_upper()
[qemu/cris-port.git] / scripts / qapi.py
blob7330f7cc64b8ac024429af2043eb665808abe10d
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 de_camel_case(name):
733 new_name = ''
734 for ch in name:
735 if ch.isupper() and new_name:
736 new_name += '_'
737 if ch == '-':
738 new_name += '_'
739 else:
740 new_name += ch.lower()
741 return new_name
743 def camel_case(name):
744 new_name = ''
745 first = True
746 for ch in name:
747 if ch in ['_', '-']:
748 first = True
749 elif first:
750 new_name += ch.upper()
751 first = False
752 else:
753 new_name += ch.lower()
754 return new_name
756 c_name_trans = string.maketrans('.-', '__')
758 def c_name(name, protect=True):
759 # ANSI X3J11/88-090, 3.1.1
760 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
761 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
762 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
763 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
764 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
765 # ISO/IEC 9899:1999, 6.4.1
766 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
767 # ISO/IEC 9899:2011, 6.4.1
768 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
769 '_Static_assert', '_Thread_local'])
770 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
771 # excluding _.*
772 gcc_words = set(['asm', 'typeof'])
773 # C++ ISO/IEC 14882:2003 2.11
774 cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
775 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
776 'namespace', 'new', 'operator', 'private', 'protected',
777 'public', 'reinterpret_cast', 'static_cast', 'template',
778 'this', 'throw', 'true', 'try', 'typeid', 'typename',
779 'using', 'virtual', 'wchar_t',
780 # alternative representations
781 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
782 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
783 # namespace pollution:
784 polluted_words = set(['unix', 'errno'])
785 if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
786 return "q_" + name
787 return name.translate(c_name_trans)
789 def c_list_type(name):
790 return '%sList' % name
792 def type_name(name):
793 if type(name) == list:
794 return c_list_type(name[0])
795 return name
797 def add_name(name, info, meta, implicit = False):
798 global all_names
799 check_name(info, "'%s'" % meta, name)
800 if name in all_names:
801 raise QAPIExprError(info,
802 "%s '%s' is already defined"
803 % (all_names[name], name))
804 if not implicit and name[-4:] == 'Kind':
805 raise QAPIExprError(info,
806 "%s '%s' should not end in 'Kind'"
807 % (meta, name))
808 all_names[name] = meta
810 def add_struct(definition, info):
811 global struct_types
812 name = definition['struct']
813 add_name(name, info, 'struct')
814 struct_types.append(definition)
816 def find_struct(name):
817 global struct_types
818 for struct in struct_types:
819 if struct['struct'] == name:
820 return struct
821 return None
823 def add_union(definition, info):
824 global union_types
825 name = definition['union']
826 add_name(name, info, 'union')
827 union_types.append(definition)
829 def find_union(name):
830 global union_types
831 for union in union_types:
832 if union['union'] == name:
833 return union
834 return None
836 def add_enum(name, info, enum_values = None, implicit = False):
837 global enum_types
838 add_name(name, info, 'enum', implicit)
839 enum_types.append({"enum_name": name, "enum_values": enum_values})
841 def find_enum(name):
842 global enum_types
843 for enum in enum_types:
844 if enum['enum_name'] == name:
845 return enum
846 return None
848 def is_enum(name):
849 return find_enum(name) != None
851 eatspace = '\033EATSPACE.'
853 # A special suffix is added in c_type() for pointer types, and it's
854 # stripped in mcgen(). So please notice this when you check the return
855 # value of c_type() outside mcgen().
856 def c_type(name, is_param=False):
857 if name == 'str':
858 if is_param:
859 return 'const char *' + eatspace
860 return 'char *' + eatspace
862 elif name == 'int':
863 return 'int64_t'
864 elif (name == 'int8' or name == 'int16' or name == 'int32' or
865 name == 'int64' or name == 'uint8' or name == 'uint16' or
866 name == 'uint32' or name == 'uint64'):
867 return name + '_t'
868 elif name == 'size':
869 return 'uint64_t'
870 elif name == 'bool':
871 return 'bool'
872 elif name == 'number':
873 return 'double'
874 elif type(name) == list:
875 return '%s *%s' % (c_list_type(name[0]), eatspace)
876 elif is_enum(name):
877 return name
878 elif name == None or len(name) == 0:
879 return 'void'
880 elif name in events:
881 return '%sEvent *%s' % (camel_case(name), eatspace)
882 else:
883 return '%s *%s' % (name, eatspace)
885 def is_c_ptr(name):
886 suffix = "*" + eatspace
887 return c_type(name).endswith(suffix)
889 def genindent(count):
890 ret = ""
891 for i in range(count):
892 ret += " "
893 return ret
895 indent_level = 0
897 def push_indent(indent_amount=4):
898 global indent_level
899 indent_level += indent_amount
901 def pop_indent(indent_amount=4):
902 global indent_level
903 indent_level -= indent_amount
905 def cgen(code, **kwds):
906 indent = genindent(indent_level)
907 lines = code.split('\n')
908 lines = map(lambda x: indent + x, lines)
909 return '\n'.join(lines) % kwds + '\n'
911 def mcgen(code, **kwds):
912 raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
913 return re.sub(re.escape(eatspace) + ' *', '', raw)
915 def basename(filename):
916 return filename.split("/")[-1]
918 def guardname(filename):
919 guard = basename(filename).rsplit(".", 1)[0]
920 for substr in [".", " ", "-"]:
921 guard = guard.replace(substr, "_")
922 return guard.upper() + '_H'
924 def guardstart(name):
925 return mcgen('''
927 #ifndef %(name)s
928 #define %(name)s
930 ''',
931 name=guardname(name))
933 def guardend(name):
934 return mcgen('''
936 #endif /* %(name)s */
938 ''',
939 name=guardname(name))
941 # ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
942 # ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
943 # ENUM24_Name -> ENUM24_NAME
944 def camel_to_upper(value):
945 c_fun_str = c_name(value, False)
946 if value.isupper():
947 return c_fun_str
949 new_name = ''
950 l = len(c_fun_str)
951 for i in range(l):
952 c = c_fun_str[i]
953 # When c is upper and no "_" appears before, do more checks
954 if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
955 # Case 1: next string is lower
956 # Case 2: previous string is digit
957 if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
958 c_fun_str[i - 1].isdigit():
959 new_name += '_'
960 new_name += c
961 return new_name.lstrip('_').upper()
963 def generate_enum_full_value(enum_name, enum_value):
964 abbrev_string = camel_to_upper(enum_name)
965 value_string = camel_to_upper(enum_value)
966 return "%s_%s" % (abbrev_string, value_string)