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