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