4 # Copyright IBM, Corp. 2011
5 # Copyright (c) 2013-2015 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.
15 from ordereddict
import OrderedDict
20 'str': 'QTYPE_QSTRING',
22 'number': 'QTYPE_QFLOAT',
23 'bool': 'QTYPE_QBOOL',
25 'int16': 'QTYPE_QINT',
26 'int32': 'QTYPE_QINT',
27 'int64': 'QTYPE_QINT',
28 'uint8': 'QTYPE_QINT',
29 'uint16': 'QTYPE_QINT',
30 'uint32': 'QTYPE_QINT',
31 'uint64': 'QTYPE_QINT',
35 def error_path(parent
):
38 res
= ("In file included from %s:%d:\n" % (parent
['file'],
39 parent
['line'])) + res
40 parent
= parent
['parent']
43 class QAPISchemaError(Exception):
44 def __init__(self
, schema
, msg
):
45 self
.input_file
= schema
.input_file
48 self
.line
= schema
.line
49 for ch
in schema
.src
[schema
.line_pos
:schema
.pos
]:
51 self
.col
= (self
.col
+ 7) % 8 + 1
54 self
.info
= schema
.parent_info
57 return error_path(self
.info
) + \
58 "%s:%d:%d: %s" % (self
.input_file
, self
.line
, self
.col
, self
.msg
)
60 class QAPIExprError(Exception):
61 def __init__(self
, expr_info
, msg
):
66 return error_path(self
.info
['parent']) + \
67 "%s:%d: %s" % (self
.info
['file'], self
.info
['line'], self
.msg
)
71 def __init__(self
, fp
, input_relname
=None, include_hist
=[],
72 previously_included
=[], parent_info
=None):
73 """ include_hist is a stack used to detect inclusion cycles
74 previously_included is a global state used to avoid multiple
75 inclusions of the same file"""
76 input_fname
= os
.path
.abspath(fp
.name
)
77 if input_relname
is None:
78 input_relname
= fp
.name
79 self
.input_dir
= os
.path
.dirname(input_fname
)
80 self
.input_file
= input_relname
81 self
.include_hist
= include_hist
+ [(input_relname
, input_fname
)]
82 previously_included
.append(input_fname
)
83 self
.parent_info
= parent_info
85 if self
.src
== '' or self
.src
[-1] != '\n':
93 while self
.tok
!= None:
94 expr_info
= {'file': input_relname
, 'line': self
.line
, 'parent': self
.parent_info
}
95 expr
= self
.get_expr(False)
96 if isinstance(expr
, dict) and "include" in expr
:
98 raise QAPIExprError(expr_info
, "Invalid 'include' directive")
99 include
= expr
["include"]
100 if not isinstance(include
, str):
101 raise QAPIExprError(expr_info
,
102 'Expected a file name (string), got: %s'
104 include_path
= os
.path
.join(self
.input_dir
, include
)
105 for elem
in self
.include_hist
:
106 if include_path
== elem
[1]:
107 raise QAPIExprError(expr_info
, "Inclusion loop for %s"
109 # skip multiple include of the same file
110 if include_path
in previously_included
:
113 fobj
= open(include_path
, 'r')
115 raise QAPIExprError(expr_info
,
116 '%s: %s' % (e
.strerror
, include
))
117 exprs_include
= QAPISchema(fobj
, include
, self
.include_hist
,
118 previously_included
, expr_info
)
119 self
.exprs
.extend(exprs_include
.exprs
)
121 expr_elem
= {'expr': expr
,
123 self
.exprs
.append(expr_elem
)
127 self
.tok
= self
.src
[self
.cursor
]
128 self
.pos
= self
.cursor
133 self
.cursor
= self
.src
.find('\n', self
.cursor
)
134 elif self
.tok
in ['{', '}', ':', ',', '[', ']']:
136 elif self
.tok
== "'":
140 ch
= self
.src
[self
.cursor
]
143 raise QAPISchemaError(self
,
144 'Missing terminating "\'"')
155 elif self
.tok
== '\n':
156 if self
.cursor
== len(self
.src
):
160 self
.line_pos
= self
.cursor
161 elif not self
.tok
.isspace():
162 raise QAPISchemaError(self
, 'Stray "%s"' % self
.tok
)
164 def get_members(self
):
170 raise QAPISchemaError(self
, 'Expected string or "}"')
175 raise QAPISchemaError(self
, 'Expected ":"')
178 raise QAPISchemaError(self
, 'Duplicate key "%s"' % key
)
179 expr
[key
] = self
.get_expr(True)
184 raise QAPISchemaError(self
, 'Expected "," or "}"')
187 raise QAPISchemaError(self
, 'Expected string')
189 def get_values(self
):
194 if not self
.tok
in [ '{', '[', "'" ]:
195 raise QAPISchemaError(self
, 'Expected "{", "[", "]" or string')
197 expr
.append(self
.get_expr(True))
202 raise QAPISchemaError(self
, 'Expected "," or "]"')
205 def get_expr(self
, nested
):
206 if self
.tok
!= '{' and not nested
:
207 raise QAPISchemaError(self
, 'Expected "{"')
210 expr
= self
.get_members()
211 elif self
.tok
== '[':
213 expr
= self
.get_values()
214 elif self
.tok
== "'":
218 raise QAPISchemaError(self
, 'Expected "{", "[" or string')
221 def find_base_fields(base
):
222 base_struct_define
= find_struct(base
)
223 if not base_struct_define
:
225 return base_struct_define
['data']
227 # Return the discriminator enum define if discriminator is specified as an
228 # enum type, otherwise return None.
229 def discriminator_find_enum_define(expr
):
230 base
= expr
.get('base')
231 discriminator
= expr
.get('discriminator')
233 if not (discriminator
and base
):
236 base_fields
= find_base_fields(base
)
240 discriminator_type
= base_fields
.get(discriminator
)
241 if not discriminator_type
:
244 return find_enum(discriminator_type
)
246 def check_event(expr
, expr_info
):
247 params
= expr
.get('data')
249 for argname
, argentry
, optional
, structured
in parse_args(params
):
251 raise QAPIExprError(expr_info
,
252 "Nested structure define in event is not "
253 "supported, event '%s', argname '%s'"
254 % (expr
['event'], argname
))
256 def check_union(expr
, expr_info
):
258 base
= expr
.get('base')
259 discriminator
= expr
.get('discriminator')
260 members
= expr
['data']
262 # If the object has a member 'base', its value must name a complex type.
264 base_fields
= find_base_fields(base
)
266 raise QAPIExprError(expr_info
,
267 "Base '%s' is not a valid type"
270 # If the union object has no member 'discriminator', it's an
272 if not discriminator
:
275 # Else if the value of member 'discriminator' is {}, it's an
277 elif discriminator
== {}:
280 # Else, it's a flat union.
282 # The object must have a member 'base'.
284 raise QAPIExprError(expr_info
,
285 "Flat union '%s' must have a base field"
287 # The value of member 'discriminator' must name a member of the
289 discriminator_type
= base_fields
.get(discriminator
)
290 if not discriminator_type
:
291 raise QAPIExprError(expr_info
,
292 "Discriminator '%s' is not a member of base "
294 % (discriminator
, base
))
295 enum_define
= find_enum(discriminator_type
)
296 # Do not allow string discriminator
298 raise QAPIExprError(expr_info
,
299 "Discriminator '%s' must be of enumeration "
300 "type" % discriminator
)
303 for (key
, value
) in members
.items():
304 # If this named member's value names an enum type, then all members
305 # of 'data' must also be members of the enum type.
306 if enum_define
and not key
in enum_define
['enum_values']:
307 raise QAPIExprError(expr_info
,
308 "Discriminator value '%s' is not found in "
310 (key
, enum_define
["enum_name"]))
311 # Todo: add checking for values. Key is checked as above, value can be
312 # also checked here, but we need more functions to handle array case.
314 def check_enum(expr
, expr_info
):
316 members
= expr
.get('data')
317 values
= { 'MAX': '(automatic)' }
319 if not isinstance(members
, list):
320 raise QAPIExprError(expr_info
,
321 "Enum '%s' requires an array for 'data'" % name
)
322 for member
in members
:
323 if not isinstance(member
, str):
324 raise QAPIExprError(expr_info
,
325 "Enum '%s' member '%s' is not a string"
327 key
= _generate_enum_string(member
)
329 raise QAPIExprError(expr_info
,
330 "Enum '%s' member '%s' clashes with '%s'"
331 % (name
, member
, values
[key
]))
334 def check_exprs(schema
):
335 for expr_elem
in schema
.exprs
:
336 expr
= expr_elem
['expr']
337 info
= expr_elem
['info']
339 if expr
.has_key('enum'):
340 check_enum(expr
, info
)
341 elif expr
.has_key('union'):
342 check_union(expr
, info
)
343 elif expr
.has_key('event'):
344 check_event(expr
, info
)
346 def parse_schema(input_file
):
348 schema
= QAPISchema(open(input_file
, "r"))
349 except (QAPISchemaError
, QAPIExprError
), e
:
350 print >>sys
.stderr
, e
355 for expr_elem
in schema
.exprs
:
356 expr
= expr_elem
['expr']
357 if expr
.has_key('enum'):
358 add_enum(expr
['enum'], expr
.get('data'))
359 elif expr
.has_key('union'):
361 elif expr
.has_key('type'):
365 # Try again for hidden UnionKind enum
366 for expr_elem
in schema
.exprs
:
367 expr
= expr_elem
['expr']
368 if expr
.has_key('union'):
369 if not discriminator_find_enum_define(expr
):
370 add_enum('%sKind' % expr
['union'])
374 except QAPIExprError
, e
:
375 print >>sys
.stderr
, e
380 def parse_args(typeinfo
):
381 if isinstance(typeinfo
, str):
382 struct
= find_struct(typeinfo
)
383 assert struct
!= None
384 typeinfo
= struct
['data']
386 for member
in typeinfo
:
388 argentry
= typeinfo
[member
]
391 if member
.startswith('*'):
394 if isinstance(argentry
, OrderedDict
):
396 yield (argname
, argentry
, optional
, structured
)
398 def de_camel_case(name
):
401 if ch
.isupper() and new_name
:
406 new_name
+= ch
.lower()
409 def camel_case(name
):
416 new_name
+= ch
.upper()
419 new_name
+= ch
.lower()
422 def c_var(name
, protect
=True):
423 # ANSI X3J11/88-090, 3.1.1
424 c89_words
= set(['auto', 'break', 'case', 'char', 'const', 'continue',
425 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
426 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
427 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
428 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
429 # ISO/IEC 9899:1999, 6.4.1
430 c99_words
= set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
431 # ISO/IEC 9899:2011, 6.4.1
432 c11_words
= set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
433 '_Static_assert', '_Thread_local'])
434 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
436 gcc_words
= set(['asm', 'typeof'])
437 # C++ ISO/IEC 14882:2003 2.11
438 cpp_words
= set(['bool', 'catch', 'class', 'const_cast', 'delete',
439 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
440 'namespace', 'new', 'operator', 'private', 'protected',
441 'public', 'reinterpret_cast', 'static_cast', 'template',
442 'this', 'throw', 'true', 'try', 'typeid', 'typename',
443 'using', 'virtual', 'wchar_t',
444 # alternative representations
445 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
446 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
447 # namespace pollution:
448 polluted_words
= set(['unix', 'errno'])
449 if protect
and (name
in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words
):
451 return name
.replace('-', '_').lstrip("*")
453 def c_fun(name
, protect
=True):
454 return c_var(name
, protect
).replace('.', '_')
456 def c_list_type(name
):
457 return '%sList' % name
460 if type(name
) == list:
461 return c_list_type(name
[0])
468 def add_struct(definition
):
470 struct_types
.append(definition
)
472 def find_struct(name
):
474 for struct
in struct_types
:
475 if struct
['type'] == name
:
479 def add_union(definition
):
481 union_types
.append(definition
)
483 def find_union(name
):
485 for union
in union_types
:
486 if union
['union'] == name
:
490 def add_enum(name
, enum_values
= None):
492 enum_types
.append({"enum_name": name
, "enum_values": enum_values
})
496 for enum
in enum_types
:
497 if enum
['enum_name'] == name
:
502 return find_enum(name
) != None
504 eatspace
= '\033EATSPACE.'
506 # A special suffix is added in c_type() for pointer types, and it's
507 # stripped in mcgen(). So please notice this when you check the return
508 # value of c_type() outside mcgen().
509 def c_type(name
, is_param
=False):
512 return 'const char *' + eatspace
513 return 'char *' + eatspace
517 elif (name
== 'int8' or name
== 'int16' or name
== 'int32' or
518 name
== 'int64' or name
== 'uint8' or name
== 'uint16' or
519 name
== 'uint32' or name
== 'uint64'):
525 elif name
== 'number':
527 elif type(name
) == list:
528 return '%s *%s' % (c_list_type(name
[0]), eatspace
)
531 elif name
== None or len(name
) == 0:
533 elif name
== name
.upper():
534 return '%sEvent *%s' % (camel_case(name
), eatspace
)
536 return '%s *%s' % (name
, eatspace
)
539 suffix
= "*" + eatspace
540 return c_type(name
).endswith(suffix
)
542 def genindent(count
):
544 for i
in range(count
):
550 def push_indent(indent_amount
=4):
552 indent_level
+= indent_amount
554 def pop_indent(indent_amount
=4):
556 indent_level
-= indent_amount
558 def cgen(code
, **kwds
):
559 indent
= genindent(indent_level
)
560 lines
= code
.split('\n')
561 lines
= map(lambda x
: indent
+ x
, lines
)
562 return '\n'.join(lines
) % kwds
+ '\n'
564 def mcgen(code
, **kwds
):
565 raw
= cgen('\n'.join(code
.split('\n')[1:-1]), **kwds
)
566 return re
.sub(re
.escape(eatspace
) + ' *', '', raw
)
568 def basename(filename
):
569 return filename
.split("/")[-1]
571 def guardname(filename
):
572 guard
= basename(filename
).rsplit(".", 1)[0]
573 for substr
in [".", " ", "-"]:
574 guard
= guard
.replace(substr
, "_")
575 return guard
.upper() + '_H'
577 def guardstart(name
):
584 name
=guardname(name
))
589 #endif /* %(name)s */
592 name
=guardname(name
))
594 # ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
595 # ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
596 # ENUM24_Name -> ENUM24_NAME
597 def _generate_enum_string(value
):
598 c_fun_str
= c_fun(value
, False)
606 # When c is upper and no "_" appears before, do more checks
607 if c
.isupper() and (i
> 0) and c_fun_str
[i
- 1] != "_":
608 # Case 1: next string is lower
609 # Case 2: previous string is digit
610 if (i
< (l
- 1) and c_fun_str
[i
+ 1].islower()) or \
611 c_fun_str
[i
- 1].isdigit():
614 return new_name
.lstrip('_').upper()
616 def generate_enum_full_value(enum_name
, enum_value
):
617 abbrev_string
= _generate_enum_string(enum_name
)
618 value_string
= _generate_enum_string(enum_value
)
619 return "%s_%s" % (abbrev_string
, value_string
)