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