2
0

common.py 6.4 KB

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