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