common.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. import string
  15. # ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
  16. # ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
  17. # ENUM24_Name -> ENUM24_NAME
  18. def camel_to_upper(value):
  19. c_fun_str = c_name(value, False)
  20. if value.isupper():
  21. return c_fun_str
  22. new_name = ''
  23. length = len(c_fun_str)
  24. for i in range(length):
  25. c = c_fun_str[i]
  26. # When c is upper and no '_' appears before, do more checks
  27. if c.isupper() and (i > 0) and c_fun_str[i - 1] != '_':
  28. if i < length - 1 and c_fun_str[i + 1].islower():
  29. new_name += '_'
  30. elif c_fun_str[i - 1].isdigit():
  31. new_name += '_'
  32. new_name += c
  33. return new_name.lstrip('_').upper()
  34. def c_enum_const(type_name, const_name, prefix=None):
  35. if prefix is not None:
  36. type_name = prefix
  37. return camel_to_upper(type_name) + '_' + c_name(const_name, False).upper()
  38. if hasattr(str, 'maketrans'):
  39. c_name_trans = str.maketrans('.-', '__')
  40. else:
  41. c_name_trans = string.maketrans('.-', '__')
  42. # Map @name to a valid C identifier.
  43. # If @protect, avoid returning certain ticklish identifiers (like
  44. # C keywords) by prepending 'q_'.
  45. #
  46. # Used for converting 'name' from a 'name':'type' qapi definition
  47. # into a generated struct member, as well as converting type names
  48. # into substrings of a generated C function name.
  49. # '__a.b_c' -> '__a_b_c', 'x-foo' -> 'x_foo'
  50. # protect=True: 'int' -> 'q_int'; protect=False: 'int' -> 'int'
  51. def c_name(name, protect=True):
  52. # ANSI X3J11/88-090, 3.1.1
  53. c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
  54. 'default', 'do', 'double', 'else', 'enum', 'extern',
  55. 'float', 'for', 'goto', 'if', 'int', 'long', 'register',
  56. 'return', 'short', 'signed', 'sizeof', 'static',
  57. 'struct', 'switch', 'typedef', 'union', 'unsigned',
  58. 'void', 'volatile', 'while'])
  59. # ISO/IEC 9899:1999, 6.4.1
  60. c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
  61. # ISO/IEC 9899:2011, 6.4.1
  62. c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic',
  63. '_Noreturn', '_Static_assert', '_Thread_local'])
  64. # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
  65. # excluding _.*
  66. gcc_words = set(['asm', 'typeof'])
  67. # C++ ISO/IEC 14882:2003 2.11
  68. cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
  69. 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
  70. 'namespace', 'new', 'operator', 'private', 'protected',
  71. 'public', 'reinterpret_cast', 'static_cast', 'template',
  72. 'this', 'throw', 'true', 'try', 'typeid', 'typename',
  73. 'using', 'virtual', 'wchar_t',
  74. # alternative representations
  75. 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
  76. 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
  77. # namespace pollution:
  78. polluted_words = set(['unix', 'errno', 'mips', 'sparc', 'i386'])
  79. name = name.translate(c_name_trans)
  80. if protect and (name in c89_words | c99_words | c11_words | gcc_words
  81. | cpp_words | polluted_words):
  82. return 'q_' + name
  83. return name
  84. eatspace = '\033EATSPACE.'
  85. pointer_suffix = ' *' + eatspace
  86. def genindent(count):
  87. ret = ''
  88. for _ in range(count):
  89. ret += ' '
  90. return ret
  91. indent_level = 0
  92. def push_indent(indent_amount=4):
  93. global indent_level
  94. indent_level += indent_amount
  95. def pop_indent(indent_amount=4):
  96. global indent_level
  97. indent_level -= indent_amount
  98. # Generate @code with @kwds interpolated.
  99. # Obey indent_level, and strip eatspace.
  100. def cgen(code, **kwds):
  101. raw = code % kwds
  102. if indent_level:
  103. indent = genindent(indent_level)
  104. # re.subn() lacks flags support before Python 2.7, use re.compile()
  105. raw = re.subn(re.compile(r'^(?!(#|$))', re.MULTILINE),
  106. indent, raw)
  107. raw = raw[0]
  108. return re.sub(re.escape(eatspace) + r' *', '', raw)
  109. def mcgen(code, **kwds):
  110. if code[0] == '\n':
  111. code = code[1:]
  112. return cgen(code, **kwds)
  113. def c_fname(filename):
  114. return re.sub(r'[^A-Za-z0-9_]', '_', filename)
  115. def guardstart(name):
  116. return mcgen('''
  117. #ifndef %(name)s
  118. #define %(name)s
  119. ''',
  120. name=c_fname(name).upper())
  121. def guardend(name):
  122. return mcgen('''
  123. #endif /* %(name)s */
  124. ''',
  125. name=c_fname(name).upper())
  126. def gen_if(ifcond):
  127. ret = ''
  128. for ifc in ifcond:
  129. ret += mcgen('''
  130. #if %(cond)s
  131. ''', cond=ifc)
  132. return ret
  133. def gen_endif(ifcond):
  134. ret = ''
  135. for ifc in reversed(ifcond):
  136. ret += mcgen('''
  137. #endif /* %(cond)s */
  138. ''', cond=ifc)
  139. return ret
  140. def build_params(arg_type, boxed, extra=None):
  141. ret = ''
  142. sep = ''
  143. if boxed:
  144. assert arg_type
  145. ret += '%s arg' % arg_type.c_param_type()
  146. sep = ', '
  147. elif arg_type:
  148. assert not arg_type.variants
  149. for memb in arg_type.members:
  150. ret += sep
  151. sep = ', '
  152. if memb.optional:
  153. ret += 'bool has_%s, ' % c_name(memb.name)
  154. ret += '%s %s' % (memb.type.c_param_type(),
  155. c_name(memb.name))
  156. if extra:
  157. ret += sep + extra
  158. return ret if ret else 'void'