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 GPL, version 2.
12 # See the COPYING 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
):
43 self
.line
= schema
.line
44 for ch
in schema
.src
[schema
.line_pos
:schema
.pos
]:
46 self
.col
= (self
.col
+ 7) % 8 + 1
51 return "%s:%s:%s: %s" % (self
.fp
.name
, self
.line
, self
.col
, self
.msg
)
53 class QAPIExprError(Exception):
54 def __init__(self
, expr_info
, msg
):
55 self
.fp
= expr_info
['fp']
56 self
.line
= expr_info
['line']
60 return "%s:%s: %s" % (self
.fp
.name
, self
.line
, self
.msg
)
64 def __init__(self
, fp
):
67 if self
.src
== '' or self
.src
[-1] != '\n':
75 while self
.tok
!= None:
76 expr_info
= {'fp': fp
, 'line': self
.line
}
77 expr_elem
= {'expr': self
.get_expr(False),
79 self
.exprs
.append(expr_elem
)
83 self
.tok
= self
.src
[self
.cursor
]
84 self
.pos
= self
.cursor
89 self
.cursor
= self
.src
.find('\n', self
.cursor
)
90 elif self
.tok
in ['{', '}', ':', ',', '[', ']']:
96 ch
= self
.src
[self
.cursor
]
99 raise QAPISchemaError(self
,
100 'Missing terminating "\'"')
111 elif self
.tok
== '\n':
112 if self
.cursor
== len(self
.src
):
116 self
.line_pos
= self
.cursor
117 elif not self
.tok
.isspace():
118 raise QAPISchemaError(self
, 'Stray "%s"' % self
.tok
)
120 def get_members(self
):
126 raise QAPISchemaError(self
, 'Expected string or "}"')
131 raise QAPISchemaError(self
, 'Expected ":"')
134 raise QAPISchemaError(self
, 'Duplicate key "%s"' % key
)
135 expr
[key
] = self
.get_expr(True)
140 raise QAPISchemaError(self
, 'Expected "," or "}"')
143 raise QAPISchemaError(self
, 'Expected string')
145 def get_values(self
):
150 if not self
.tok
in [ '{', '[', "'" ]:
151 raise QAPISchemaError(self
, 'Expected "{", "[", "]" or string')
153 expr
.append(self
.get_expr(True))
158 raise QAPISchemaError(self
, 'Expected "," or "]"')
161 def get_expr(self
, nested
):
162 if self
.tok
!= '{' and not nested
:
163 raise QAPISchemaError(self
, 'Expected "{"')
166 expr
= self
.get_members()
167 elif self
.tok
== '[':
169 expr
= self
.get_values()
170 elif self
.tok
== "'":
174 raise QAPISchemaError(self
, 'Expected "{", "[" or string')
177 def find_base_fields(base
):
178 base_struct_define
= find_struct(base
)
179 if not base_struct_define
:
181 return base_struct_define
['data']
183 # Return the discriminator enum define if discriminator is specified as an
184 # enum type, otherwise return None.
185 def discriminator_find_enum_define(expr
):
186 base
= expr
.get('base')
187 discriminator
= expr
.get('discriminator')
189 if not (discriminator
and base
):
192 base_fields
= find_base_fields(base
)
196 discriminator_type
= base_fields
.get(discriminator
)
197 if not discriminator_type
:
200 return find_enum(discriminator_type
)
202 def check_union(expr
, expr_info
):
204 base
= expr
.get('base')
205 discriminator
= expr
.get('discriminator')
206 members
= expr
['data']
208 # If the object has a member 'base', its value must name a complex type.
210 base_fields
= find_base_fields(base
)
212 raise QAPIExprError(expr_info
,
213 "Base '%s' is not a valid type"
216 # If the union object has no member 'discriminator', it's an
218 if not discriminator
:
221 # Else if the value of member 'discriminator' is {}, it's an
223 elif discriminator
== {}:
226 # Else, it's a flat union.
228 # The object must have a member 'base'.
230 raise QAPIExprError(expr_info
,
231 "Flat union '%s' must have a base field"
233 # The value of member 'discriminator' must name a member of the
235 discriminator_type
= base_fields
.get(discriminator
)
236 if not discriminator_type
:
237 raise QAPIExprError(expr_info
,
238 "Discriminator '%s' is not a member of base "
240 % (discriminator
, base
))
241 enum_define
= find_enum(discriminator_type
)
242 # Do not allow string discriminator
244 raise QAPIExprError(expr_info
,
245 "Discriminator '%s' must be of enumeration "
246 "type" % discriminator
)
249 for (key
, value
) in members
.items():
250 # If this named member's value names an enum type, then all members
251 # of 'data' must also be members of the enum type.
252 if enum_define
and not key
in enum_define
['enum_values']:
253 raise QAPIExprError(expr_info
,
254 "Discriminator value '%s' is not found in "
256 (key
, enum_define
["enum_name"]))
257 # Todo: add checking for values. Key is checked as above, value can be
258 # also checked here, but we need more functions to handle array case.
260 def check_exprs(schema
):
261 for expr_elem
in schema
.exprs
:
262 expr
= expr_elem
['expr']
263 if expr
.has_key('union'):
264 check_union(expr
, expr_elem
['info'])
266 def parse_schema(fp
):
268 schema
= QAPISchema(fp
)
269 except QAPISchemaError
, e
:
270 print >>sys
.stderr
, e
275 for expr_elem
in schema
.exprs
:
276 expr
= expr_elem
['expr']
277 if expr
.has_key('enum'):
278 add_enum(expr
['enum'], expr
['data'])
279 elif expr
.has_key('union'):
281 elif expr
.has_key('type'):
285 # Try again for hidden UnionKind enum
286 for expr_elem
in schema
.exprs
:
287 expr
= expr_elem
['expr']
288 if expr
.has_key('union'):
289 if not discriminator_find_enum_define(expr
):
290 add_enum('%sKind' % expr
['union'])
294 except QAPIExprError
, e
:
295 print >>sys
.stderr
, e
300 def parse_args(typeinfo
):
301 if isinstance(typeinfo
, basestring
):
302 struct
= find_struct(typeinfo
)
303 assert struct
!= None
304 typeinfo
= struct
['data']
306 for member
in typeinfo
:
308 argentry
= typeinfo
[member
]
311 if member
.startswith('*'):
314 if isinstance(argentry
, OrderedDict
):
316 yield (argname
, argentry
, optional
, structured
)
318 def de_camel_case(name
):
321 if ch
.isupper() and new_name
:
326 new_name
+= ch
.lower()
329 def camel_case(name
):
336 new_name
+= ch
.upper()
339 new_name
+= ch
.lower()
342 def c_var(name
, protect
=True):
343 # ANSI X3J11/88-090, 3.1.1
344 c89_words
= set(['auto', 'break', 'case', 'char', 'const', 'continue',
345 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
346 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
347 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
348 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
349 # ISO/IEC 9899:1999, 6.4.1
350 c99_words
= set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
351 # ISO/IEC 9899:2011, 6.4.1
352 c11_words
= set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
353 '_Static_assert', '_Thread_local'])
354 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
356 gcc_words
= set(['asm', 'typeof'])
357 # C++ ISO/IEC 14882:2003 2.11
358 cpp_words
= set(['bool', 'catch', 'class', 'const_cast', 'delete',
359 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
360 'namespace', 'new', 'operator', 'private', 'protected',
361 'public', 'reinterpret_cast', 'static_cast', 'template',
362 'this', 'throw', 'true', 'try', 'typeid', 'typename',
363 'using', 'virtual', 'wchar_t',
364 # alternative representations
365 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
366 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
367 # namespace pollution:
368 polluted_words
= set(['unix', 'errno'])
369 if protect
and (name
in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words
):
371 return name
.replace('-', '_').lstrip("*")
373 def c_fun(name
, protect
=True):
374 return c_var(name
, protect
).replace('.', '_')
376 def c_list_type(name
):
377 return '%sList' % name
380 if type(name
) == list:
381 return c_list_type(name
[0])
388 def add_struct(definition
):
390 struct_types
.append(definition
)
392 def find_struct(name
):
394 for struct
in struct_types
:
395 if struct
['type'] == name
:
399 def add_union(definition
):
401 union_types
.append(definition
)
403 def find_union(name
):
405 for union
in union_types
:
406 if union
['union'] == name
:
410 def add_enum(name
, enum_values
= None):
412 enum_types
.append({"enum_name": name
, "enum_values": enum_values
})
416 for enum
in enum_types
:
417 if enum
['enum_name'] == name
:
422 return find_enum(name
) != None
429 elif (name
== 'int8' or name
== 'int16' or name
== 'int32' or
430 name
== 'int64' or name
== 'uint8' or name
== 'uint16' or
431 name
== 'uint32' or name
== 'uint64'):
437 elif name
== 'number':
439 elif type(name
) == list:
440 return '%s *' % c_list_type(name
[0])
443 elif name
== None or len(name
) == 0:
445 elif name
== name
.upper():
446 return '%sEvent *' % camel_case(name
)
450 def genindent(count
):
452 for i
in range(count
):
458 def push_indent(indent_amount
=4):
460 indent_level
+= indent_amount
462 def pop_indent(indent_amount
=4):
464 indent_level
-= indent_amount
466 def cgen(code
, **kwds
):
467 indent
= genindent(indent_level
)
468 lines
= code
.split('\n')
469 lines
= map(lambda x
: indent
+ x
, lines
)
470 return '\n'.join(lines
) % kwds
+ '\n'
472 def mcgen(code
, **kwds
):
473 return cgen('\n'.join(code
.split('\n')[1:-1]), **kwds
)
475 def basename(filename
):
476 return filename
.split("/")[-1]
478 def guardname(filename
):
479 guard
= basename(filename
).rsplit(".", 1)[0]
480 for substr
in [".", " ", "-"]:
481 guard
= guard
.replace(substr
, "_")
482 return guard
.upper() + '_H'
484 def guardstart(name
):
491 name
=guardname(name
))
496 #endif /* %(name)s */
499 name
=guardname(name
))
501 # ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
502 # ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
503 # ENUM24_Name -> ENUM24_NAME
504 def _generate_enum_string(value
):
505 c_fun_str
= c_fun(value
, False)
513 # When c is upper and no "_" appears before, do more checks
514 if c
.isupper() and (i
> 0) and c_fun_str
[i
- 1] != "_":
515 # Case 1: next string is lower
516 # Case 2: previous string is digit
517 if (i
< (l
- 1) and c_fun_str
[i
+ 1].islower()) or \
518 c_fun_str
[i
- 1].isdigit():
521 return new_name
.lstrip('_').upper()
523 def generate_enum_full_value(enum_name
, enum_value
):
524 abbrev_string
= _generate_enum_string(enum_name
)
525 value_string
= _generate_enum_string(enum_value
)
526 return "%s_%s" % (abbrev_string
, value_string
)