2
0

common.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. ret = value[0]
  37. upc = value[0].isupper()
  38. # Copy remainder of ``value`` to ``ret`` with '_' inserted
  39. for ch in value[1:]:
  40. if ch.isupper() == upc:
  41. pass
  42. elif upc:
  43. # ``ret`` ends in upper case, next char isn't: insert '_'
  44. # before the last upper case char unless there is one
  45. # already, or it's at the beginning
  46. if len(ret) > 2 and ret[-2].isalnum():
  47. ret = ret[:-1] + '_' + ret[-1]
  48. else:
  49. # ``ret`` doesn't end in upper case, next char is: insert
  50. # '_' before it
  51. if ret[-1].isalnum():
  52. ret += '_'
  53. ret += ch
  54. upc = ch.isupper()
  55. return c_name(ret.upper()).lstrip('_')
  56. def c_enum_const(type_name: str,
  57. const_name: str,
  58. prefix: Optional[str] = None) -> str:
  59. """
  60. Generate a C enumeration constant name.
  61. :param type_name: The name of the enumeration.
  62. :param const_name: The name of this constant.
  63. :param prefix: Optional, prefix that overrides the type_name.
  64. """
  65. if prefix is None:
  66. prefix = camel_to_upper(type_name)
  67. return prefix + '_' + c_name(const_name, False).upper()
  68. def c_name(name: str, protect: bool = True) -> str:
  69. """
  70. Map ``name`` to a valid C identifier.
  71. Used for converting 'name' from a 'name':'type' qapi definition
  72. into a generated struct member, as well as converting type names
  73. into substrings of a generated C function name.
  74. '__a.b_c' -> '__a_b_c', 'x-foo' -> 'x_foo'
  75. protect=True: 'int' -> 'q_int'; protect=False: 'int' -> 'int'
  76. :param name: The name to map.
  77. :param protect: If true, avoid returning certain ticklish identifiers
  78. (like C keywords) by prepending ``q_``.
  79. """
  80. # ANSI X3J11/88-090, 3.1.1
  81. c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
  82. 'default', 'do', 'double', 'else', 'enum', 'extern',
  83. 'float', 'for', 'goto', 'if', 'int', 'long', 'register',
  84. 'return', 'short', 'signed', 'sizeof', 'static',
  85. 'struct', 'switch', 'typedef', 'union', 'unsigned',
  86. 'void', 'volatile', 'while'])
  87. # ISO/IEC 9899:1999, 6.4.1
  88. c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
  89. # ISO/IEC 9899:2011, 6.4.1
  90. c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic',
  91. '_Noreturn', '_Static_assert', '_Thread_local'])
  92. # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
  93. # excluding _.*
  94. gcc_words = set(['asm', 'typeof'])
  95. # C++ ISO/IEC 14882:2003 2.11
  96. cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
  97. 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
  98. 'namespace', 'new', 'operator', 'private', 'protected',
  99. 'public', 'reinterpret_cast', 'static_cast', 'template',
  100. 'this', 'throw', 'true', 'try', 'typeid', 'typename',
  101. 'using', 'virtual', 'wchar_t',
  102. # alternative representations
  103. 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
  104. 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
  105. # namespace pollution:
  106. polluted_words = set(['unix', 'errno', 'mips', 'sparc', 'i386', 'linux'])
  107. name = re.sub(r'[^A-Za-z0-9_]', '_', name)
  108. if protect and (name in (c89_words | c99_words | c11_words | gcc_words
  109. | cpp_words | polluted_words)
  110. or name[0].isdigit()):
  111. return 'q_' + name
  112. return name
  113. class Indentation:
  114. """
  115. Indentation level management.
  116. :param initial: Initial number of spaces, default 0.
  117. """
  118. def __init__(self, initial: int = 0) -> None:
  119. self._level = initial
  120. def __repr__(self) -> str:
  121. return "{}({:d})".format(type(self).__name__, self._level)
  122. def __str__(self) -> str:
  123. """Return the current indentation as a string of spaces."""
  124. return ' ' * self._level
  125. def increase(self, amount: int = 4) -> None:
  126. """Increase the indentation level by ``amount``, default 4."""
  127. self._level += amount
  128. def decrease(self, amount: int = 4) -> None:
  129. """Decrease the indentation level by ``amount``, default 4."""
  130. assert amount <= self._level
  131. self._level -= amount
  132. #: Global, current indent level for code generation.
  133. indent = Indentation()
  134. def cgen(code: str, **kwds: object) -> str:
  135. """
  136. Generate ``code`` with ``kwds`` interpolated.
  137. Obey `indent`, and strip `EATSPACE`.
  138. """
  139. raw = code % kwds
  140. pfx = str(indent)
  141. if pfx:
  142. raw = re.sub(r'^(?!(#|$))', pfx, 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 gen_ifcond(ifcond: Optional[Union[str, Dict[str, Any]]],
  162. cond_fmt: str, not_fmt: str,
  163. all_operator: str, any_operator: str) -> str:
  164. def do_gen(ifcond: Union[str, Dict[str, Any]],
  165. need_parens: bool) -> str:
  166. if isinstance(ifcond, str):
  167. return cond_fmt % ifcond
  168. assert isinstance(ifcond, dict) and len(ifcond) == 1
  169. if 'not' in ifcond:
  170. return not_fmt % do_gen(ifcond['not'], True)
  171. if 'all' in ifcond:
  172. gen = gen_infix(all_operator, ifcond['all'])
  173. else:
  174. gen = gen_infix(any_operator, ifcond['any'])
  175. if need_parens:
  176. gen = '(' + gen + ')'
  177. return gen
  178. def gen_infix(operator: str, operands: Sequence[Any]) -> str:
  179. return operator.join([do_gen(o, True) for o in operands])
  180. if not ifcond:
  181. return ''
  182. return do_gen(ifcond, False)
  183. def cgen_ifcond(ifcond: Optional[Union[str, Dict[str, Any]]]) -> str:
  184. return gen_ifcond(ifcond, 'defined(%s)', '!%s', ' && ', ' || ')
  185. def docgen_ifcond(ifcond: Optional[Union[str, Dict[str, Any]]]) -> str:
  186. # TODO Doc generated for conditions needs polish
  187. return gen_ifcond(ifcond, '%s', 'not %s', ' and ', ' or ')
  188. def gen_if(cond: str) -> str:
  189. if not cond:
  190. return ''
  191. return mcgen('''
  192. #if %(cond)s
  193. ''', cond=cond)
  194. def gen_endif(cond: str) -> str:
  195. if not cond:
  196. return ''
  197. return mcgen('''
  198. #endif /* %(cond)s */
  199. ''', cond=cond)
  200. def must_match(pattern: str, string: str) -> Match[str]:
  201. match = re.match(pattern, string)
  202. assert match is not None
  203. return match