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