4 # Copyright IBM, Corp. 2011
5 # Copyright (c) 2013 Red Hat Inc.
8 # Anthony Liguori <aliguori@us.ibm.com>
9 # Markus Armbruster <armbru@redhat.com>
11 # This work is licensed under the terms of the GNU GPLv2.
12 # See the COPYING.LIB file in the top-level directory.
14 from ordereddict
import OrderedDict
18 'str', 'int', 'number', 'bool',
19 'int8', 'int16', 'int32', 'int64',
20 'uint8', 'uint16', 'uint32', 'uint64'
23 builtin_type_qtypes
= {
24 'str': 'QTYPE_QSTRING',
26 'number': 'QTYPE_QFLOAT',
27 'bool': 'QTYPE_QBOOL',
29 'int16': 'QTYPE_QINT',
30 'int32': 'QTYPE_QINT',
31 'int64': 'QTYPE_QINT',
32 'uint8': 'QTYPE_QINT',
33 'uint16': 'QTYPE_QINT',
34 'uint32': 'QTYPE_QINT',
35 'uint64': 'QTYPE_QINT',
38 class QAPISchemaError(Exception):
39 def __init__(self
, schema
, msg
):
42 self
.line
= self
.col
= 1
43 for ch
in schema
.src
[0:schema
.pos
]:
48 self
.col
= (self
.col
+ 7) % 8 + 1
53 return "%s:%s:%s: %s" % (self
.fp
.name
, self
.line
, self
.col
, self
.msg
)
57 def __init__(self
, fp
):
60 if self
.src
== '' or self
.src
[-1] != '\n':
66 while self
.tok
!= None:
67 self
.exprs
.append(self
.get_expr(False))
71 self
.tok
= self
.src
[self
.cursor
]
72 self
.pos
= self
.cursor
77 self
.cursor
= self
.src
.find('\n', self
.cursor
)
78 elif self
.tok
in ['{', '}', ':', ',', '[', ']']:
84 ch
= self
.src
[self
.cursor
]
87 raise QAPISchemaError(self
,
88 'Missing terminating "\'"')
99 elif self
.tok
== '\n':
100 if self
.cursor
== len(self
.src
):
103 elif not self
.tok
.isspace():
104 raise QAPISchemaError(self
, 'Stray "%s"' % self
.tok
)
106 def get_members(self
):
112 raise QAPISchemaError(self
, 'Expected string or "}"')
117 raise QAPISchemaError(self
, 'Expected ":"')
119 expr
[key
] = self
.get_expr(True)
124 raise QAPISchemaError(self
, 'Expected "," or "}"')
127 raise QAPISchemaError(self
, 'Expected string')
129 def get_values(self
):
134 if not self
.tok
in [ '{', '[', "'" ]:
135 raise QAPISchemaError(self
, 'Expected "{", "[", "]" or string')
137 expr
.append(self
.get_expr(True))
142 raise QAPISchemaError(self
, 'Expected "," or "]"')
145 def get_expr(self
, nested
):
146 if self
.tok
!= '{' and not nested
:
147 raise QAPISchemaError(self
, 'Expected "{"')
150 expr
= self
.get_members()
151 elif self
.tok
== '[':
153 expr
= self
.get_values()
154 elif self
.tok
== "'":
158 raise QAPISchemaError(self
, 'Expected "{", "[" or string')
161 def parse_schema(fp
):
163 schema
= QAPISchema(fp
)
164 except QAPISchemaError
as e
:
165 print >>sys
.stderr
, e
170 for expr
in schema
.exprs
:
171 if expr
.has_key('enum'):
172 add_enum(expr
['enum'])
173 elif expr
.has_key('union'):
175 add_enum('%sKind' % expr
['union'])
176 elif expr
.has_key('type'):
182 def parse_args(typeinfo
):
183 if isinstance(typeinfo
, basestring
):
184 struct
= find_struct(typeinfo
)
185 assert struct
!= None
186 typeinfo
= struct
['data']
188 for member
in typeinfo
:
190 argentry
= typeinfo
[member
]
193 if member
.startswith('*'):
196 if isinstance(argentry
, OrderedDict
):
198 yield (argname
, argentry
, optional
, structured
)
200 def de_camel_case(name
):
203 if ch
.isupper() and new_name
:
208 new_name
+= ch
.lower()
211 def camel_case(name
):
218 new_name
+= ch
.upper()
221 new_name
+= ch
.lower()
224 def c_var(name
, protect
=True):
225 # ANSI X3J11/88-090, 3.1.1
226 c89_words
= set(['auto', 'break', 'case', 'char', 'const', 'continue',
227 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
228 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
229 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
230 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
231 # ISO/IEC 9899:1999, 6.4.1
232 c99_words
= set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
233 # ISO/IEC 9899:2011, 6.4.1
234 c11_words
= set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
235 '_Static_assert', '_Thread_local'])
236 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
238 gcc_words
= set(['asm', 'typeof'])
239 # namespace pollution:
240 polluted_words
= set(['unix'])
241 if protect
and (name
in c89_words | c99_words | c11_words | gcc_words | polluted_words
):
243 return name
.replace('-', '_').lstrip("*")
245 def c_fun(name
, protect
=True):
246 return c_var(name
, protect
).replace('.', '_')
248 def c_list_type(name
):
249 return '%sList' % name
252 if type(name
) == list:
253 return c_list_type(name
[0])
260 def add_struct(definition
):
262 struct_types
.append(definition
)
264 def find_struct(name
):
266 for struct
in struct_types
:
267 if struct
['type'] == name
:
271 def add_union(definition
):
273 union_types
.append(definition
)
275 def find_union(name
):
277 for union
in union_types
:
278 if union
['union'] == name
:
284 enum_types
.append(name
)
288 return (name
in enum_types
)
295 elif (name
== 'int8' or name
== 'int16' or name
== 'int32' or
296 name
== 'int64' or name
== 'uint8' or name
== 'uint16' or
297 name
== 'uint32' or name
== 'uint64'):
303 elif name
== 'number':
305 elif type(name
) == list:
306 return '%s *' % c_list_type(name
[0])
309 elif name
== None or len(name
) == 0:
311 elif name
== name
.upper():
312 return '%sEvent *' % camel_case(name
)
316 def genindent(count
):
318 for i
in range(count
):
324 def push_indent(indent_amount
=4):
326 indent_level
+= indent_amount
328 def pop_indent(indent_amount
=4):
330 indent_level
-= indent_amount
332 def cgen(code
, **kwds
):
333 indent
= genindent(indent_level
)
334 lines
= code
.split('\n')
335 lines
= map(lambda x
: indent
+ x
, lines
)
336 return '\n'.join(lines
) % kwds
+ '\n'
338 def mcgen(code
, **kwds
):
339 return cgen('\n'.join(code
.split('\n')[1:-1]), **kwds
)
341 def basename(filename
):
342 return filename
.split("/")[-1]
344 def guardname(filename
):
345 guard
= basename(filename
).rsplit(".", 1)[0]
346 for substr
in [".", " ", "-"]:
347 guard
= guard
.replace(substr
, "_")
348 return guard
.upper() + '_H'
350 def guardstart(name
):
357 name
=guardname(name
))
362 #endif /* %(name)s */
365 name
=guardname(name
))