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