2
0

common.py 7.4 KB

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