2
0

common.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. #
  2. # QAPI helper library
  3. #
  4. # Copyright IBM, Corp. 2011
  5. # Copyright (c) 2013-2018 Red Hat Inc.
  6. #
  7. # Authors:
  8. # Anthony Liguori <aliguori@us.ibm.com>
  9. # Markus Armbruster <armbru@redhat.com>
  10. #
  11. # This work is licensed under the terms of the GNU GPL, version 2.
  12. # See the COPYING file in the top-level directory.
  13. import re
  14. EATSPACE = '\033EATSPACE.'
  15. POINTER_SUFFIX = ' *' + EATSPACE
  16. _C_NAME_TRANS = str.maketrans('.-', '__')
  17. # ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
  18. # ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
  19. # ENUM24_Name -> ENUM24_NAME
  20. def camel_to_upper(value):
  21. c_fun_str = c_name(value, False)
  22. if value.isupper():
  23. return c_fun_str
  24. new_name = ''
  25. length = len(c_fun_str)
  26. for i in range(length):
  27. c = c_fun_str[i]
  28. # When c is upper and no '_' appears before, do more checks
  29. if c.isupper() and (i > 0) and c_fun_str[i - 1] != '_':
  30. if i < length - 1 and c_fun_str[i + 1].islower():
  31. new_name += '_'
  32. elif c_fun_str[i - 1].isdigit():
  33. new_name += '_'
  34. new_name += c
  35. return new_name.lstrip('_').upper()
  36. def c_enum_const(type_name, const_name, prefix=None):
  37. if prefix is not None:
  38. type_name = prefix
  39. return camel_to_upper(type_name) + '_' + c_name(const_name, False).upper()
  40. # Map @name to a valid C identifier.
  41. # If @protect, avoid returning certain ticklish identifiers (like
  42. # C keywords) by prepending 'q_'.
  43. #
  44. # Used for converting 'name' from a 'name':'type' qapi definition
  45. # into a generated struct member, as well as converting type names
  46. # into substrings of a generated C function name.
  47. # '__a.b_c' -> '__a_b_c', 'x-foo' -> 'x_foo'
  48. # protect=True: 'int' -> 'q_int'; protect=False: 'int' -> 'int'
  49. def c_name(name, protect=True):
  50. # ANSI X3J11/88-090, 3.1.1
  51. c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
  52. 'default', 'do', 'double', 'else', 'enum', 'extern',
  53. 'float', 'for', 'goto', 'if', 'int', 'long', 'register',
  54. 'return', 'short', 'signed', 'sizeof', 'static',
  55. 'struct', 'switch', 'typedef', 'union', 'unsigned',
  56. 'void', 'volatile', 'while'])
  57. # ISO/IEC 9899:1999, 6.4.1
  58. c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
  59. # ISO/IEC 9899:2011, 6.4.1
  60. c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic',
  61. '_Noreturn', '_Static_assert', '_Thread_local'])
  62. # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
  63. # excluding _.*
  64. gcc_words = set(['asm', 'typeof'])
  65. # C++ ISO/IEC 14882:2003 2.11
  66. cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
  67. 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
  68. 'namespace', 'new', 'operator', 'private', 'protected',
  69. 'public', 'reinterpret_cast', 'static_cast', 'template',
  70. 'this', 'throw', 'true', 'try', 'typeid', 'typename',
  71. 'using', 'virtual', 'wchar_t',
  72. # alternative representations
  73. 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
  74. 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
  75. # namespace pollution:
  76. polluted_words = set(['unix', 'errno', 'mips', 'sparc', 'i386'])
  77. name = name.translate(_C_NAME_TRANS)
  78. if protect and (name in c89_words | c99_words | c11_words | gcc_words
  79. | cpp_words | polluted_words):
  80. return 'q_' + name
  81. return name
  82. class Indentation:
  83. """
  84. Indentation level management.
  85. :param initial: Initial number of spaces, default 0.
  86. """
  87. def __init__(self, initial: int = 0) -> None:
  88. self._level = initial
  89. def __int__(self) -> int:
  90. return self._level
  91. def __repr__(self) -> str:
  92. return "{}({:d})".format(type(self).__name__, self._level)
  93. def __str__(self) -> str:
  94. """Return the current indentation as a string of spaces."""
  95. return ' ' * self._level
  96. def __bool__(self) -> bool:
  97. """True when there is a non-zero indentation."""
  98. return bool(self._level)
  99. def increase(self, amount: int = 4) -> None:
  100. """Increase the indentation level by ``amount``, default 4."""
  101. self._level += amount
  102. def decrease(self, amount: int = 4) -> None:
  103. """Decrease the indentation level by ``amount``, default 4."""
  104. if self._level < amount:
  105. raise ArithmeticError(
  106. f"Can't remove {amount:d} spaces from {self!r}")
  107. self._level -= amount
  108. indent = Indentation()
  109. # Generate @code with @kwds interpolated.
  110. # Obey indent, and strip EATSPACE.
  111. def cgen(code, **kwds):
  112. raw = code % kwds
  113. if indent:
  114. raw = re.sub(r'^(?!(#|$))', str(indent), raw, flags=re.MULTILINE)
  115. return re.sub(re.escape(EATSPACE) + r' *', '', raw)
  116. def mcgen(code, **kwds):
  117. if code[0] == '\n':
  118. code = code[1:]
  119. return cgen(code, **kwds)
  120. def c_fname(filename):
  121. return re.sub(r'[^A-Za-z0-9_]', '_', filename)
  122. def guardstart(name):
  123. return mcgen('''
  124. #ifndef %(name)s
  125. #define %(name)s
  126. ''',
  127. name=c_fname(name).upper())
  128. def guardend(name):
  129. return mcgen('''
  130. #endif /* %(name)s */
  131. ''',
  132. name=c_fname(name).upper())
  133. def gen_if(ifcond):
  134. ret = ''
  135. for ifc in ifcond:
  136. ret += mcgen('''
  137. #if %(cond)s
  138. ''', cond=ifc)
  139. return ret
  140. def gen_endif(ifcond):
  141. ret = ''
  142. for ifc in reversed(ifcond):
  143. ret += mcgen('''
  144. #endif /* %(cond)s */
  145. ''', cond=ifc)
  146. return ret
  147. def build_params(arg_type, boxed, extra=None):
  148. ret = ''
  149. sep = ''
  150. if boxed:
  151. assert arg_type
  152. ret += '%s arg' % arg_type.c_param_type()
  153. sep = ', '
  154. elif arg_type:
  155. assert not arg_type.variants
  156. for memb in arg_type.members:
  157. ret += sep
  158. sep = ', '
  159. if memb.optional:
  160. ret += 'bool has_%s, ' % c_name(memb.name)
  161. ret += '%s %s' % (memb.type.c_param_type(),
  162. c_name(memb.name))
  163. if extra:
  164. ret += sep + extra
  165. return ret if ret else 'void'