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