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