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