qapi: Split up scripts/qapi/common.py
[qemu/ar7.git] / scripts / qapi / common.py
blobe00dcafce7705cc81e5e22d1269245a8df3ef120
2 # QAPI helper library
4 # Copyright IBM, Corp. 2011
5 # Copyright (c) 2013-2018 Red Hat Inc.
7 # Authors:
8 # Anthony Liguori <aliguori@us.ibm.com>
9 # Markus Armbruster <armbru@redhat.com>
11 # This work is licensed under the terms of the GNU GPL, version 2.
12 # See the COPYING file in the top-level directory.
14 import re
15 import string
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
21 def camel_to_upper(value):
22 c_fun_str = c_name(value, False)
23 if value.isupper():
24 return c_fun_str
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()
40 def 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()
46 if hasattr(str, 'maketrans'):
47 c_name_trans = str.maketrans('.-', '__')
48 else:
49 c_name_trans = string.maketrans('.-', '__')
52 # Map @name to a valid C identifier.
53 # If @protect, avoid returning certain ticklish identifiers (like
54 # C keywords) by prepending 'q_'.
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'
61 def 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
96 eatspace = '\033EATSPACE.'
97 pointer_suffix = ' *' + eatspace
100 def genindent(count):
101 ret = ''
102 for _ in range(count):
103 ret += ' '
104 return ret
107 indent_level = 0
110 def push_indent(indent_amount=4):
111 global indent_level
112 indent_level += indent_amount
115 def pop_indent(indent_amount=4):
116 global indent_level
117 indent_level -= indent_amount
120 # Generate @code with @kwds interpolated.
121 # Obey indent_level, and strip eatspace.
122 def 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)
133 def mcgen(code, **kwds):
134 if code[0] == '\n':
135 code = code[1:]
136 return cgen(code, **kwds)
139 def c_fname(filename):
140 return re.sub(r'[^A-Za-z0-9_]', '_', filename)
143 def guardstart(name):
144 return mcgen('''
145 #ifndef %(name)s
146 #define %(name)s
148 ''',
149 name=c_fname(name).upper())
152 def guardend(name):
153 return mcgen('''
155 #endif /* %(name)s */
156 ''',
157 name=c_fname(name).upper())
160 def gen_if(ifcond):
161 ret = ''
162 for ifc in ifcond:
163 ret += mcgen('''
164 #if %(cond)s
165 ''', cond=ifc)
166 return ret
169 def gen_endif(ifcond):
170 ret = ''
171 for ifc in reversed(ifcond):
172 ret += mcgen('''
173 #endif /* %(cond)s */
174 ''', cond=ifc)
175 return ret
178 def 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'