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
23 'str': 'QTYPE_QSTRING',
25 'number': 'QTYPE_QFLOAT',
26 'bool': 'QTYPE_QBOOL',
28 'int16': 'QTYPE_QINT',
29 'int32': 'QTYPE_QINT',
30 'int64': 'QTYPE_QINT',
31 'uint8': 'QTYPE_QINT',
32 'uint16': 'QTYPE_QINT',
33 'uint32': 'QTYPE_QINT',
34 'uint64': 'QTYPE_QINT',
38 # Whitelist of commands allowed to return a non-dictionary
41 'human-monitor-command',
42 'query-migrate-cache-size',
49 'guest-fsfreeze-freeze',
50 'guest-fsfreeze-freeze-list',
51 'guest-fsfreeze-status',
52 'guest-fsfreeze-thaw',
56 'guest-sync-delimited',
58 # From qapi-schema-test:
69 # Parsing the schema into expressions
72 def error_path(parent
):
75 res
= ("In file included from %s:%d:\n" % (parent
['file'],
76 parent
['line'])) + res
77 parent
= parent
['parent']
80 class QAPISchemaError(Exception):
81 def __init__(self
, schema
, msg
):
82 self
.fname
= schema
.fname
85 self
.line
= schema
.line
86 for ch
in schema
.src
[schema
.line_pos
:schema
.pos
]:
88 self
.col
= (self
.col
+ 7) % 8 + 1
91 self
.info
= schema
.incl_info
94 return error_path(self
.info
) + \
95 "%s:%d:%d: %s" % (self
.fname
, self
.line
, self
.col
, self
.msg
)
97 class QAPIExprError(Exception):
98 def __init__(self
, expr_info
, msg
):
103 return error_path(self
.info
['parent']) + \
104 "%s:%d: %s" % (self
.info
['file'], self
.info
['line'], self
.msg
)
108 def __init__(self
, fp
, previously_included
= [], incl_info
= None):
109 abs_fname
= os
.path
.abspath(fp
.name
)
112 previously_included
.append(abs_fname
)
113 self
.incl_info
= incl_info
115 if self
.src
== '' or self
.src
[-1] != '\n':
123 while self
.tok
!= None:
124 expr_info
= {'file': fname
, 'line': self
.line
,
125 'parent': self
.incl_info
}
126 expr
= self
.get_expr(False)
127 if isinstance(expr
, dict) and "include" in expr
:
129 raise QAPIExprError(expr_info
, "Invalid 'include' directive")
130 include
= expr
["include"]
131 if not isinstance(include
, str):
132 raise QAPIExprError(expr_info
,
133 'Expected a file name (string), got: %s'
135 incl_abs_fname
= os
.path
.join(os
.path
.dirname(abs_fname
),
137 # catch inclusion cycle
140 if incl_abs_fname
== os
.path
.abspath(inf
['file']):
141 raise QAPIExprError(expr_info
, "Inclusion loop for %s"
144 # skip multiple include of the same file
145 if incl_abs_fname
in previously_included
:
148 fobj
= open(incl_abs_fname
, 'r')
150 raise QAPIExprError(expr_info
,
151 '%s: %s' % (e
.strerror
, include
))
152 exprs_include
= QAPISchema(fobj
, previously_included
,
154 self
.exprs
.extend(exprs_include
.exprs
)
156 expr_elem
= {'expr': expr
,
158 self
.exprs
.append(expr_elem
)
162 self
.tok
= self
.src
[self
.cursor
]
163 self
.pos
= self
.cursor
168 self
.cursor
= self
.src
.find('\n', self
.cursor
)
169 elif self
.tok
in ['{', '}', ':', ',', '[', ']']:
171 elif self
.tok
== "'":
175 ch
= self
.src
[self
.cursor
]
178 raise QAPISchemaError(self
,
179 'Missing terminating "\'"')
193 for x
in range(0, 4):
194 ch
= self
.src
[self
.cursor
]
196 if ch
not in "0123456789abcdefABCDEF":
197 raise QAPISchemaError(self
,
198 '\\u escape needs 4 '
200 value
= (value
<< 4) + int(ch
, 16)
201 # If Python 2 and 3 didn't disagree so much on
202 # how to handle Unicode, then we could allow
203 # Unicode string defaults. But most of QAPI is
204 # ASCII-only, so we aren't losing much for now.
205 if not value
or value
> 0x7f:
206 raise QAPISchemaError(self
,
207 'For now, \\u escape '
208 'only supports non-zero '
209 'values up to \\u007f')
214 raise QAPISchemaError(self
,
215 "Unknown escape \\%s" %ch
)
224 elif self
.src
.startswith("true", self
.pos
):
228 elif self
.src
.startswith("false", self
.pos
):
232 elif self
.src
.startswith("null", self
.pos
):
236 elif self
.tok
== '\n':
237 if self
.cursor
== len(self
.src
):
241 self
.line_pos
= self
.cursor
242 elif not self
.tok
.isspace():
243 raise QAPISchemaError(self
, 'Stray "%s"' % self
.tok
)
245 def get_members(self
):
251 raise QAPISchemaError(self
, 'Expected string or "}"')
256 raise QAPISchemaError(self
, 'Expected ":"')
259 raise QAPISchemaError(self
, 'Duplicate key "%s"' % key
)
260 expr
[key
] = self
.get_expr(True)
265 raise QAPISchemaError(self
, 'Expected "," or "}"')
268 raise QAPISchemaError(self
, 'Expected string')
270 def get_values(self
):
275 if not self
.tok
in "{['tfn":
276 raise QAPISchemaError(self
, 'Expected "{", "[", "]", string, '
279 expr
.append(self
.get_expr(True))
284 raise QAPISchemaError(self
, 'Expected "," or "]"')
287 def get_expr(self
, nested
):
288 if self
.tok
!= '{' and not nested
:
289 raise QAPISchemaError(self
, 'Expected "{"')
292 expr
= self
.get_members()
293 elif self
.tok
== '[':
295 expr
= self
.get_values()
296 elif self
.tok
in "'tfn":
300 raise QAPISchemaError(self
, 'Expected "{", "[" or string')
304 # Semantic analysis of schema expressions
307 def find_base_fields(base
):
308 base_struct_define
= find_struct(base
)
309 if not base_struct_define
:
311 return base_struct_define
['data']
313 # Return the qtype of an alternate branch, or None on error.
314 def find_alternate_member_qtype(qapi_type
):
315 if builtin_types
.has_key(qapi_type
):
316 return builtin_types
[qapi_type
]
317 elif find_struct(qapi_type
):
319 elif find_enum(qapi_type
):
320 return "QTYPE_QSTRING"
321 elif find_union(qapi_type
):
325 # Return the discriminator enum define if discriminator is specified as an
326 # enum type, otherwise return None.
327 def discriminator_find_enum_define(expr
):
328 base
= expr
.get('base')
329 discriminator
= expr
.get('discriminator')
331 if not (discriminator
and base
):
334 base_fields
= find_base_fields(base
)
338 discriminator_type
= base_fields
.get(discriminator
)
339 if not discriminator_type
:
342 return find_enum(discriminator_type
)
344 valid_name
= re
.compile('^[a-zA-Z_][a-zA-Z0-9_.-]*$')
345 def check_name(expr_info
, source
, name
, allow_optional
= False,
346 enum_member
= False):
350 if not isinstance(name
, str):
351 raise QAPIExprError(expr_info
,
352 "%s requires a string name" % source
)
353 if name
.startswith('*'):
354 membername
= name
[1:]
355 if not allow_optional
:
356 raise QAPIExprError(expr_info
,
357 "%s does not allow optional name '%s'"
359 # Enum members can start with a digit, because the generated C
360 # code always prefixes it with the enum name
362 membername
= '_' + membername
363 if not valid_name
.match(membername
):
364 raise QAPIExprError(expr_info
,
365 "%s uses invalid name '%s'" % (source
, name
))
367 def add_name(name
, info
, meta
, implicit
= False):
369 check_name(info
, "'%s'" % meta
, name
)
370 if name
in all_names
:
371 raise QAPIExprError(info
,
372 "%s '%s' is already defined"
373 % (all_names
[name
], name
))
374 if not implicit
and name
[-4:] == 'Kind':
375 raise QAPIExprError(info
,
376 "%s '%s' should not end in 'Kind'"
378 all_names
[name
] = meta
380 def add_struct(definition
, info
):
382 name
= definition
['struct']
383 add_name(name
, info
, 'struct')
384 struct_types
.append(definition
)
386 def find_struct(name
):
388 for struct
in struct_types
:
389 if struct
['struct'] == name
:
393 def add_union(definition
, info
):
395 name
= definition
['union']
396 add_name(name
, info
, 'union')
397 union_types
.append(definition
)
399 def find_union(name
):
401 for union
in union_types
:
402 if union
['union'] == name
:
406 def add_enum(name
, info
, enum_values
= None, implicit
= False):
408 add_name(name
, info
, 'enum', implicit
)
409 enum_types
.append({"enum_name": name
, "enum_values": enum_values
})
413 for enum
in enum_types
:
414 if enum
['enum_name'] == name
:
419 return find_enum(name
) != None
421 def check_type(expr_info
, source
, value
, allow_array
= False,
422 allow_dict
= False, allow_optional
= False,
423 allow_star
= False, allow_metas
= []):
430 if allow_star
and value
== '**':
433 # Check if array type for value is okay
434 if isinstance(value
, list):
436 raise QAPIExprError(expr_info
,
437 "%s cannot be an array" % source
)
438 if len(value
) != 1 or not isinstance(value
[0], str):
439 raise QAPIExprError(expr_info
,
440 "%s: array type must contain single type name"
443 orig_value
= "array of %s" %value
445 # Check if type name for value is okay
446 if isinstance(value
, str):
448 raise QAPIExprError(expr_info
,
449 "%s uses '**' but did not request 'gen':false"
451 if not value
in all_names
:
452 raise QAPIExprError(expr_info
,
453 "%s uses unknown type '%s'"
454 % (source
, orig_value
))
455 if not all_names
[value
] in allow_metas
:
456 raise QAPIExprError(expr_info
,
457 "%s cannot use %s type '%s'"
458 % (source
, all_names
[value
], orig_value
))
461 # value is a dictionary, check that each member is okay
462 if not isinstance(value
, OrderedDict
):
463 raise QAPIExprError(expr_info
,
464 "%s should be a dictionary" % source
)
466 raise QAPIExprError(expr_info
,
467 "%s should be a type name" % source
)
468 for (key
, arg
) in value
.items():
469 check_name(expr_info
, "Member of %s" % source
, key
,
470 allow_optional
=allow_optional
)
471 # Todo: allow dictionaries to represent default values of
472 # an optional argument.
473 check_type(expr_info
, "Member '%s' of %s" % (key
, source
), arg
,
474 allow_array
=True, allow_star
=allow_star
,
475 allow_metas
=['built-in', 'union', 'alternate', 'struct',
478 def check_member_clash(expr_info
, base_name
, data
, source
= ""):
479 base
= find_struct(base_name
)
481 base_members
= base
['data']
482 for key
in data
.keys():
483 if key
.startswith('*'):
485 if key
in base_members
or "*" + key
in base_members
:
486 raise QAPIExprError(expr_info
,
487 "Member name '%s'%s clashes with base '%s'"
488 % (key
, source
, base_name
))
490 check_member_clash(expr_info
, base
['base'], data
, source
)
492 def check_command(expr
, expr_info
):
493 name
= expr
['command']
494 allow_star
= expr
.has_key('gen')
496 check_type(expr_info
, "'data' for command '%s'" % name
,
497 expr
.get('data'), allow_dict
=True, allow_optional
=True,
498 allow_metas
=['union', 'struct'], allow_star
=allow_star
)
499 returns_meta
= ['union', 'struct']
500 if name
in returns_whitelist
:
501 returns_meta
+= ['built-in', 'alternate', 'enum']
502 check_type(expr_info
, "'returns' for command '%s'" % name
,
503 expr
.get('returns'), allow_array
=True, allow_dict
=True,
504 allow_optional
=True, allow_metas
=returns_meta
,
505 allow_star
=allow_star
)
507 def check_event(expr
, expr_info
):
510 params
= expr
.get('data')
512 if name
.upper() == 'MAX':
513 raise QAPIExprError(expr_info
, "Event name 'MAX' cannot be created")
515 check_type(expr_info
, "'data' for event '%s'" % name
,
516 expr
.get('data'), allow_dict
=True, allow_optional
=True,
517 allow_metas
=['union', 'struct'])
519 def check_union(expr
, expr_info
):
521 base
= expr
.get('base')
522 discriminator
= expr
.get('discriminator')
523 members
= expr
['data']
524 values
= { 'MAX': '(automatic)' }
526 # If the object has a member 'base', its value must name a struct,
527 # and there must be a discriminator.
529 if discriminator
is None:
530 raise QAPIExprError(expr_info
,
531 "Union '%s' requires a discriminator to go "
532 "along with base" %name
)
534 # Two types of unions, determined by discriminator.
536 # With no discriminator it is a simple union.
537 if discriminator
is None:
539 allow_metas
=['built-in', 'union', 'alternate', 'struct', 'enum']
541 raise QAPIExprError(expr_info
,
542 "Simple union '%s' must not have a base"
545 # Else, it's a flat union.
547 # The object must have a string member 'base'.
548 if not isinstance(base
, str):
549 raise QAPIExprError(expr_info
,
550 "Flat union '%s' must have a string base field"
552 base_fields
= find_base_fields(base
)
554 raise QAPIExprError(expr_info
,
555 "Base '%s' is not a valid struct"
558 # The value of member 'discriminator' must name a non-optional
559 # member of the base struct.
560 check_name(expr_info
, "Discriminator of flat union '%s'" % name
,
562 discriminator_type
= base_fields
.get(discriminator
)
563 if not discriminator_type
:
564 raise QAPIExprError(expr_info
,
565 "Discriminator '%s' is not a member of base "
567 % (discriminator
, base
))
568 enum_define
= find_enum(discriminator_type
)
569 allow_metas
=['struct']
570 # Do not allow string discriminator
572 raise QAPIExprError(expr_info
,
573 "Discriminator '%s' must be of enumeration "
574 "type" % discriminator
)
577 for (key
, value
) in members
.items():
578 check_name(expr_info
, "Member of union '%s'" % name
, key
)
580 # Each value must name a known type; furthermore, in flat unions,
581 # branches must be a struct with no overlapping member names
582 check_type(expr_info
, "Member '%s' of union '%s'" % (key
, name
),
583 value
, allow_array
=not base
, allow_metas
=allow_metas
)
585 branch_struct
= find_struct(value
)
587 check_member_clash(expr_info
, base
, branch_struct
['data'],
588 " of branch '%s'" % key
)
590 # If the discriminator names an enum type, then all members
591 # of 'data' must also be members of the enum type.
593 if not key
in enum_define
['enum_values']:
594 raise QAPIExprError(expr_info
,
595 "Discriminator value '%s' is not found in "
597 (key
, enum_define
["enum_name"]))
599 # Otherwise, check for conflicts in the generated enum
601 c_key
= camel_to_upper(key
)
603 raise QAPIExprError(expr_info
,
604 "Union '%s' member '%s' clashes with '%s'"
605 % (name
, key
, values
[c_key
]))
608 def check_alternate(expr
, expr_info
):
609 name
= expr
['alternate']
610 members
= expr
['data']
611 values
= { 'MAX': '(automatic)' }
615 for (key
, value
) in members
.items():
616 check_name(expr_info
, "Member of alternate '%s'" % name
, key
)
618 # Check for conflicts in the generated enum
619 c_key
= camel_to_upper(key
)
621 raise QAPIExprError(expr_info
,
622 "Alternate '%s' member '%s' clashes with '%s'"
623 % (name
, key
, values
[c_key
]))
626 # Ensure alternates have no type conflicts.
627 check_type(expr_info
, "Member '%s' of alternate '%s'" % (key
, name
),
629 allow_metas
=['built-in', 'union', 'struct', 'enum'])
630 qtype
= find_alternate_member_qtype(value
)
632 if qtype
in types_seen
:
633 raise QAPIExprError(expr_info
,
634 "Alternate '%s' member '%s' can't "
635 "be distinguished from member '%s'"
636 % (name
, key
, types_seen
[qtype
]))
637 types_seen
[qtype
] = key
639 def check_enum(expr
, expr_info
):
641 members
= expr
.get('data')
642 values
= { 'MAX': '(automatic)' }
644 if not isinstance(members
, list):
645 raise QAPIExprError(expr_info
,
646 "Enum '%s' requires an array for 'data'" % name
)
647 for member
in members
:
648 check_name(expr_info
, "Member of enum '%s'" %name
, member
,
650 key
= camel_to_upper(member
)
652 raise QAPIExprError(expr_info
,
653 "Enum '%s' member '%s' clashes with '%s'"
654 % (name
, member
, values
[key
]))
657 def check_struct(expr
, expr_info
):
658 name
= expr
['struct']
659 members
= expr
['data']
661 check_type(expr_info
, "'data' for struct '%s'" % name
, members
,
662 allow_dict
=True, allow_optional
=True)
663 check_type(expr_info
, "'base' for struct '%s'" % name
, expr
.get('base'),
664 allow_metas
=['struct'])
666 check_member_clash(expr_info
, expr
['base'], expr
['data'])
668 def check_keys(expr_elem
, meta
, required
, optional
=[]):
669 expr
= expr_elem
['expr']
670 info
= expr_elem
['info']
672 if not isinstance(name
, str):
673 raise QAPIExprError(info
,
674 "'%s' key must have a string value" % meta
)
675 required
= required
+ [ meta
]
676 for (key
, value
) in expr
.items():
677 if not key
in required
and not key
in optional
:
678 raise QAPIExprError(info
,
679 "Unknown key '%s' in %s '%s'"
681 if (key
== 'gen' or key
== 'success-response') and value
!= False:
682 raise QAPIExprError(info
,
683 "'%s' of %s '%s' should only use false value"
686 if not expr
.has_key(key
):
687 raise QAPIExprError(info
,
688 "Key '%s' is missing from %s '%s'"
691 def check_exprs(exprs
):
694 # Learn the types and check for valid expression keys
695 for builtin
in builtin_types
.keys():
696 all_names
[builtin
] = 'built-in'
697 for expr_elem
in exprs
:
698 expr
= expr_elem
['expr']
699 info
= expr_elem
['info']
700 if expr
.has_key('enum'):
701 check_keys(expr_elem
, 'enum', ['data'])
702 add_enum(expr
['enum'], info
, expr
['data'])
703 elif expr
.has_key('union'):
704 check_keys(expr_elem
, 'union', ['data'],
705 ['base', 'discriminator'])
706 add_union(expr
, info
)
707 elif expr
.has_key('alternate'):
708 check_keys(expr_elem
, 'alternate', ['data'])
709 add_name(expr
['alternate'], info
, 'alternate')
710 elif expr
.has_key('struct'):
711 check_keys(expr_elem
, 'struct', ['data'], ['base'])
712 add_struct(expr
, info
)
713 elif expr
.has_key('command'):
714 check_keys(expr_elem
, 'command', [],
715 ['data', 'returns', 'gen', 'success-response'])
716 add_name(expr
['command'], info
, 'command')
717 elif expr
.has_key('event'):
718 check_keys(expr_elem
, 'event', [], ['data'])
719 add_name(expr
['event'], info
, 'event')
721 raise QAPIExprError(expr_elem
['info'],
722 "Expression is missing metatype")
724 # Try again for hidden UnionKind enum
725 for expr_elem
in exprs
:
726 expr
= expr_elem
['expr']
727 if expr
.has_key('union'):
728 if not discriminator_find_enum_define(expr
):
729 add_enum('%sKind' % expr
['union'], expr_elem
['info'],
731 elif expr
.has_key('alternate'):
732 add_enum('%sKind' % expr
['alternate'], expr_elem
['info'],
735 # Validate that exprs make sense
736 for expr_elem
in exprs
:
737 expr
= expr_elem
['expr']
738 info
= expr_elem
['info']
740 if expr
.has_key('enum'):
741 check_enum(expr
, info
)
742 elif expr
.has_key('union'):
743 check_union(expr
, info
)
744 elif expr
.has_key('alternate'):
745 check_alternate(expr
, info
)
746 elif expr
.has_key('struct'):
747 check_struct(expr
, info
)
748 elif expr
.has_key('command'):
749 check_command(expr
, info
)
750 elif expr
.has_key('event'):
751 check_event(expr
, info
)
753 assert False, 'unexpected meta type'
755 return map(lambda expr_elem
: expr_elem
['expr'], exprs
)
757 def parse_schema(fname
):
759 schema
= QAPISchema(open(fname
, "r"))
760 return check_exprs(schema
.exprs
)
761 except (QAPISchemaError
, QAPIExprError
), e
:
762 print >>sys
.stderr
, e
766 # Code generation helpers
769 def parse_args(typeinfo
):
770 if isinstance(typeinfo
, str):
771 struct
= find_struct(typeinfo
)
772 assert struct
!= None
773 typeinfo
= struct
['data']
775 for member
in typeinfo
:
777 argentry
= typeinfo
[member
]
779 if member
.startswith('*'):
782 # Todo: allow argentry to be OrderedDict, for providing the
783 # value of an optional argument.
784 yield (argname
, argentry
, optional
)
786 def camel_case(name
):
793 new_name
+= ch
.upper()
796 new_name
+= ch
.lower()
799 # ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
800 # ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
801 # ENUM24_Name -> ENUM24_NAME
802 def camel_to_upper(value
):
803 c_fun_str
= c_name(value
, False)
811 # When c is upper and no "_" appears before, do more checks
812 if c
.isupper() and (i
> 0) and c_fun_str
[i
- 1] != "_":
813 # Case 1: next string is lower
814 # Case 2: previous string is digit
815 if (i
< (l
- 1) and c_fun_str
[i
+ 1].islower()) or \
816 c_fun_str
[i
- 1].isdigit():
819 return new_name
.lstrip('_').upper()
821 def c_enum_const(type_name
, const_name
):
822 return camel_to_upper(type_name
+ '_' + const_name
)
824 c_name_trans
= string
.maketrans('.-', '__')
826 # Map @name to a valid C identifier.
827 # If @protect, avoid returning certain ticklish identifiers (like
828 # C keywords) by prepending "q_".
830 # Used for converting 'name' from a 'name':'type' qapi definition
831 # into a generated struct member, as well as converting type names
832 # into substrings of a generated C function name.
833 # '__a.b_c' -> '__a_b_c', 'x-foo' -> 'x_foo'
834 # protect=True: 'int' -> 'q_int'; protect=False: 'int' -> 'int'
835 def c_name(name
, protect
=True):
836 # ANSI X3J11/88-090, 3.1.1
837 c89_words
= set(['auto', 'break', 'case', 'char', 'const', 'continue',
838 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
839 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
840 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
841 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
842 # ISO/IEC 9899:1999, 6.4.1
843 c99_words
= set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
844 # ISO/IEC 9899:2011, 6.4.1
845 c11_words
= set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
846 '_Static_assert', '_Thread_local'])
847 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
849 gcc_words
= set(['asm', 'typeof'])
850 # C++ ISO/IEC 14882:2003 2.11
851 cpp_words
= set(['bool', 'catch', 'class', 'const_cast', 'delete',
852 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
853 'namespace', 'new', 'operator', 'private', 'protected',
854 'public', 'reinterpret_cast', 'static_cast', 'template',
855 'this', 'throw', 'true', 'try', 'typeid', 'typename',
856 'using', 'virtual', 'wchar_t',
857 # alternative representations
858 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
859 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
860 # namespace pollution:
861 polluted_words
= set(['unix', 'errno'])
862 if protect
and (name
in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words
):
864 return name
.translate(c_name_trans
)
866 # Map type @name to the C typedef name for the list form.
868 # ['Name'] -> 'NameList', ['x-Foo'] -> 'x_FooList', ['int'] -> 'intList'
869 def c_list_type(name
):
870 return type_name(name
) + 'List'
872 # Map type @value to the C typedef form.
874 # Used for converting 'type' from a 'member':'type' qapi definition
875 # into the alphanumeric portion of the type for a generated C parameter,
876 # as well as generated C function names. See c_type() for the rest of
877 # the conversion such as adding '*' on pointer types.
878 # 'int' -> 'int', '[x-Foo]' -> 'x_FooList', '__a.b_c' -> '__a_b_c'
879 def type_name(value
):
880 if type(value
) == list:
881 return c_list_type(value
[0])
882 if value
in builtin_types
.keys():
886 eatspace
= '\033EATSPACE.'
887 pointer_suffix
= ' *' + eatspace
889 # Map type @name to its C type expression.
890 # If @is_param, const-qualify the string type.
892 # This function is used for computing the full C type of 'member':'name'.
893 # A special suffix is added in c_type() for pointer types, and it's
894 # stripped in mcgen(). So please notice this when you check the return
895 # value of c_type() outside mcgen().
896 def c_type(value
, is_param
=False):
899 return 'const char' + pointer_suffix
900 return 'char' + pointer_suffix
904 elif (value
== 'int8' or value
== 'int16' or value
== 'int32' or
905 value
== 'int64' or value
== 'uint8' or value
== 'uint16' or
906 value
== 'uint32' or value
== 'uint64'):
908 elif value
== 'size':
910 elif value
== 'bool':
912 elif value
== 'number':
914 elif type(value
) == list:
915 return c_list_type(value
[0]) + pointer_suffix
920 elif value
in events
:
921 return camel_case(value
) + 'Event' + pointer_suffix
924 assert isinstance(value
, str) and value
!= ""
925 return c_name(value
) + pointer_suffix
928 return c_type(value
).endswith(pointer_suffix
)
930 def genindent(count
):
932 for i
in range(count
):
938 def push_indent(indent_amount
=4):
940 indent_level
+= indent_amount
942 def pop_indent(indent_amount
=4):
944 indent_level
-= indent_amount
946 def cgen(code
, **kwds
):
947 indent
= genindent(indent_level
)
948 lines
= code
.split('\n')
949 lines
= map(lambda x
: indent
+ x
, lines
)
950 return '\n'.join(lines
) % kwds
+ '\n'
952 def mcgen(code
, **kwds
):
953 raw
= cgen('\n'.join(code
.split('\n')[1:-1]), **kwds
)
954 return re
.sub(re
.escape(eatspace
) + ' *', '', raw
)
956 def basename(filename
):
957 return filename
.split("/")[-1]
959 def guardname(filename
):
960 guard
= basename(filename
).rsplit(".", 1)[0]
961 for substr
in [".", " ", "-"]:
962 guard
= guard
.replace(substr
, "_")
963 return guard
.upper() + '_H'
965 def guardstart(name
):
972 name
=guardname(name
))
977 #endif /* %(name)s */
980 name
=guardname(name
))
983 # Common command line parsing
986 def parse_command_line(extra_options
= "", extra_long_options
= []):
989 opts
, args
= getopt
.gnu_getopt(sys
.argv
[1:],
990 "chp:o:" + extra_options
,
991 ["source", "header", "prefix=",
992 "output-dir="] + extra_long_options
)
993 except getopt
.GetoptError
, err
:
994 print >>sys
.stderr
, "%s: %s" % (sys
.argv
[0], str(err
))
1005 if o
in ("-p", "--prefix"):
1007 elif o
in ("-o", "--output-dir"):
1008 output_dir
= a
+ "/"
1009 elif o
in ("-c", "--source"):
1011 elif o
in ("-h", "--header"):
1014 extra_opts
.append(oa
)
1016 if not do_c
and not do_h
:
1021 print >>sys
.stderr
, "%s: need exactly one argument" % sys
.argv
[0]
1025 return (fname
, output_dir
, do_c
, do_h
, prefix
, extra_opts
)
1028 # Generate output files with boilerplate
1031 def open_output(output_dir
, do_c
, do_h
, prefix
, c_file
, h_file
,
1032 c_comment
, h_comment
):
1033 c_file
= output_dir
+ prefix
+ c_file
1034 h_file
= output_dir
+ prefix
+ h_file
1037 os
.makedirs(output_dir
)
1039 if e
.errno
!= errno
.EEXIST
:
1042 def maybe_open(really
, name
, opt
):
1044 return open(name
, opt
)
1047 return StringIO
.StringIO()
1049 fdef
= maybe_open(do_c
, c_file
, 'w')
1050 fdecl
= maybe_open(do_h
, h_file
, 'w')
1052 fdef
.write(mcgen('''
1053 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
1056 comment
= c_comment
))
1058 fdecl
.write(mcgen('''
1059 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
1065 comment
= h_comment
, guard
= guardname(h_file
)))
1067 return (fdef
, fdecl
)
1069 def close_output(fdef
, fdecl
):