4 # Copyright IBM, Corp. 2011
5 # Copyright (c) 2013-2015 Red Hat Inc.
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.
15 from ordereddict
import OrderedDict
21 'str': 'QTYPE_QSTRING',
23 'number': 'QTYPE_QFLOAT',
24 'bool': 'QTYPE_QBOOL',
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',
36 # Whitelist of commands allowed to return a non-dictionary
39 'human-monitor-command',
40 'query-migrate-cache-size',
47 'guest-fsfreeze-freeze',
48 'guest-fsfreeze-freeze-list',
49 'guest-fsfreeze-status',
50 'guest-fsfreeze-thaw',
54 'guest-sync-delimited',
56 # From qapi-schema-test:
66 def error_path(parent
):
69 res
= ("In file included from %s:%d:\n" % (parent
['file'],
70 parent
['line'])) + res
71 parent
= parent
['parent']
74 class QAPISchemaError(Exception):
75 def __init__(self
, schema
, msg
):
76 self
.input_file
= schema
.input_file
79 self
.line
= schema
.line
80 for ch
in schema
.src
[schema
.line_pos
:schema
.pos
]:
82 self
.col
= (self
.col
+ 7) % 8 + 1
85 self
.info
= schema
.parent_info
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
):
97 return error_path(self
.info
['parent']) + \
98 "%s:%d: %s" % (self
.info
['file'], self
.info
['line'], self
.msg
)
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
116 if self
.src
== '' or self
.src
[-1] != '\n':
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
:
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'
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"
140 # skip multiple include of the same file
141 if include_path
in previously_included
:
144 fobj
= open(include_path
, 'r')
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
)
152 expr_elem
= {'expr': expr
,
154 self
.exprs
.append(expr_elem
)
158 self
.tok
= self
.src
[self
.cursor
]
159 self
.pos
= self
.cursor
164 self
.cursor
= self
.src
.find('\n', self
.cursor
)
165 elif self
.tok
in ['{', '}', ':', ',', '[', ']']:
167 elif self
.tok
== "'":
171 ch
= self
.src
[self
.cursor
]
174 raise QAPISchemaError(self
,
175 'Missing terminating "\'"')
189 for x
in range(0, 4):
190 ch
= self
.src
[self
.cursor
]
192 if ch
not in "0123456789abcdefABCDEF":
193 raise QAPISchemaError(self
,
194 '\\u escape needs 4 '
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')
210 raise QAPISchemaError(self
,
211 "Unknown escape \\%s" %ch
)
220 elif self
.tok
in "tfn":
221 val
= self
.src
[self
.cursor
- 1:]
222 if val
.startswith("true"):
226 elif val
.startswith("false"):
230 elif val
.startswith("null"):
234 elif self
.tok
== '\n':
235 if self
.cursor
== len(self
.src
):
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
):
249 raise QAPISchemaError(self
, 'Expected string or "}"')
254 raise QAPISchemaError(self
, 'Expected ":"')
257 raise QAPISchemaError(self
, 'Duplicate key "%s"' % key
)
258 expr
[key
] = self
.get_expr(True)
263 raise QAPISchemaError(self
, 'Expected "," or "}"')
266 raise QAPISchemaError(self
, 'Expected string')
268 def get_values(self
):
273 if not self
.tok
in "{['tfn":
274 raise QAPISchemaError(self
, 'Expected "{", "[", "]", string, '
277 expr
.append(self
.get_expr(True))
282 raise QAPISchemaError(self
, 'Expected "," or "]"')
285 def get_expr(self
, nested
):
286 if self
.tok
!= '{' and not nested
:
287 raise QAPISchemaError(self
, 'Expected "{"')
290 expr
= self
.get_members()
291 elif self
.tok
== '[':
293 expr
= self
.get_values()
294 elif self
.tok
in "'tfn":
298 raise QAPISchemaError(self
, 'Expected "{", "[" or string')
301 def find_base_fields(base
):
302 base_struct_define
= find_struct(base
)
303 if not base_struct_define
:
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
):
313 elif find_enum(qapi_type
):
314 return "QTYPE_QSTRING"
315 elif find_union(qapi_type
):
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
):
328 base_fields
= find_base_fields(base
)
332 discriminator_type
= base_fields
.get(discriminator
)
333 if not discriminator_type
:
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):
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'"
353 # Enum members can start with a digit, because the generated C
354 # code always prefixes it with the enum name
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
= []):
370 if allow_star
and value
== '**':
373 # Check if array type for value is okay
374 if isinstance(value
, list):
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"
383 orig_value
= "array of %s" %value
385 # Check if type name for value is okay
386 if isinstance(value
, str):
388 raise QAPIExprError(expr_info
,
389 "%s uses '**' but did not request 'gen':false"
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
))
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
)
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',
418 def check_member_clash(expr_info
, base_name
, data
, source
= ""):
419 base
= find_struct(base_name
)
421 base_members
= base
['data']
422 for key
in data
.keys():
423 if key
.startswith('*'):
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
))
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
):
450 params
= expr
.get('data')
452 if name
.upper() == 'MAX':
453 raise QAPIExprError(expr_info
, "Event name 'MAX' cannot be created")
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
):
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.
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:
479 allow_metas
=['built-in', 'union', 'alternate', 'struct', 'enum']
481 raise QAPIExprError(expr_info
,
482 "Simple union '%s' must not have a base"
485 # Else, it's a flat union.
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"
492 base_fields
= find_base_fields(base
)
494 raise QAPIExprError(expr_info
,
495 "Base '%s' is not a valid struct"
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
,
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 "
507 % (discriminator
, base
))
508 enum_define
= find_enum(discriminator_type
)
509 allow_metas
=['struct']
510 # Do not allow string discriminator
512 raise QAPIExprError(expr_info
,
513 "Discriminator '%s' must be of enumeration "
514 "type" % discriminator
)
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
)
525 branch_struct
= find_struct(value
)
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.
533 if not key
in enum_define
['enum_values']:
534 raise QAPIExprError(expr_info
,
535 "Discriminator value '%s' is not found in "
537 (key
, enum_define
["enum_name"]))
539 # Otherwise, check for conflicts in the generated enum
541 c_key
= camel_to_upper(key
)
543 raise QAPIExprError(expr_info
,
544 "Union '%s' member '%s' clashes with '%s'"
545 % (name
, key
, values
[c_key
]))
548 def check_alternate(expr
, expr_info
):
549 name
= expr
['alternate']
550 members
= expr
['data']
551 values
= { 'MAX': '(automatic)' }
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
)
561 raise QAPIExprError(expr_info
,
562 "Alternate '%s' member '%s' clashes with '%s'"
563 % (name
, key
, values
[c_key
]))
566 # Ensure alternates have no type conflicts.
567 check_type(expr_info
, "Member '%s' of alternate '%s'" % (key
, name
),
569 allow_metas
=['built-in', 'union', 'struct', 'enum'])
570 qtype
= find_alternate_member_qtype(value
)
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
):
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
,
590 key
= camel_to_upper(member
)
592 raise QAPIExprError(expr_info
,
593 "Enum '%s' member '%s' clashes with '%s'"
594 % (name
, member
, values
[key
]))
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'])
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
)
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']
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'"
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"
646 if not expr
.has_key(key
):
647 raise QAPIExprError(info
,
648 "Key '%s' is missing from %s '%s'"
652 def parse_schema(input_file
):
656 # First pass: read entire file into memory
658 schema
= QAPISchema(open(input_file
, "r"))
659 except (QAPISchemaError
, QAPIExprError
), e
:
660 print >>sys
.stderr
, e
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')
692 raise QAPIExprError(expr_elem
['info'],
693 "Expression is missing metatype")
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'],
703 elif expr
.has_key('alternate'):
704 add_enum('%sKind' % expr
['alternate'], expr_elem
['info'],
707 # Final pass - validate that exprs make sense
709 except QAPIExprError
, e
:
710 print >>sys
.stderr
, e
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
:
723 argentry
= typeinfo
[member
]
725 if member
.startswith('*'):
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
):
739 new_name
+= ch
.upper()
742 new_name
+= ch
.lower()
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)
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():
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
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
):
801 return name
.translate(c_name_trans
)
803 def c_list_type(name
):
806 def type_name(value
):
807 if type(value
) == list:
808 return c_list_type(value
[0])
811 def add_name(name
, info
, meta
, implicit
= False):
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'"
822 all_names
[name
] = meta
824 def add_struct(definition
, info
):
826 name
= definition
['struct']
827 add_name(name
, info
, 'struct')
828 struct_types
.append(definition
)
830 def find_struct(name
):
832 for struct
in struct_types
:
833 if struct
['struct'] == name
:
837 def add_union(definition
, info
):
839 name
= definition
['union']
840 add_name(name
, info
, 'union')
841 union_types
.append(definition
)
843 def find_union(name
):
845 for union
in union_types
:
846 if union
['union'] == name
:
850 def add_enum(name
, info
, enum_values
= None, implicit
= False):
852 add_name(name
, info
, 'enum', implicit
)
853 enum_types
.append({"enum_name": name
, "enum_values": enum_values
})
857 for enum
in enum_types
:
858 if enum
['enum_name'] == 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):
874 return 'const char' + pointer_suffix
875 return 'char' + pointer_suffix
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'):
883 elif value
== 'size':
885 elif value
== 'bool':
887 elif value
== 'number':
889 elif type(value
) == list:
890 return c_list_type(value
[0]) + pointer_suffix
895 elif value
in events
:
896 return camel_case(value
) + 'Event' + pointer_suffix
899 assert isinstance(value
, str) and value
!= ""
900 return value
+ pointer_suffix
903 return c_type(value
).endswith(pointer_suffix
)
905 def genindent(count
):
907 for i
in range(count
):
913 def push_indent(indent_amount
=4):
915 indent_level
+= indent_amount
917 def pop_indent(indent_amount
=4):
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
):
947 name
=guardname(name
))
952 #endif /* %(name)s */
955 name
=guardname(name
))