qapi-introspect.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. """
  2. QAPI introspection generator
  3. Copyright (C) 2015-2018 Red Hat, Inc.
  4. Authors:
  5. Markus Armbruster <armbru@redhat.com>
  6. This work is licensed under the terms of the GNU GPL, version 2.
  7. See the COPYING file in the top-level directory.
  8. """
  9. from qapi import *
  10. # Caveman's json.dumps() replacement (we're stuck at Python 2.4)
  11. # TODO try to use json.dumps() once we get unstuck
  12. def to_json(obj, level=0):
  13. if obj is None:
  14. ret = 'null'
  15. elif isinstance(obj, str):
  16. ret = '"' + obj.replace('"', r'\"') + '"'
  17. elif isinstance(obj, list):
  18. elts = [to_json(elt, level + 1)
  19. for elt in obj]
  20. ret = '[' + ', '.join(elts) + ']'
  21. elif isinstance(obj, dict):
  22. elts = ['"%s": %s' % (key.replace('"', r'\"'),
  23. to_json(obj[key], level + 1))
  24. for key in sorted(obj.keys())]
  25. ret = '{' + ', '.join(elts) + '}'
  26. else:
  27. assert False # not implemented
  28. if level == 1:
  29. ret = '\n' + ret
  30. return ret
  31. def to_c_string(string):
  32. return '"' + string.replace('\\', r'\\').replace('"', r'\"') + '"'
  33. class QAPISchemaGenIntrospectVisitor(QAPISchemaVisitor):
  34. def __init__(self, unmask):
  35. self._unmask = unmask
  36. self.defn = None
  37. self.decl = None
  38. self._schema = None
  39. self._jsons = None
  40. self._used_types = None
  41. self._name_map = None
  42. def visit_begin(self, schema):
  43. self._schema = schema
  44. self._jsons = []
  45. self._used_types = []
  46. self._name_map = {}
  47. def visit_end(self):
  48. # visit the types that are actually used
  49. jsons = self._jsons
  50. self._jsons = []
  51. for typ in self._used_types:
  52. typ.visit(self)
  53. # generate C
  54. # TODO can generate awfully long lines
  55. jsons.extend(self._jsons)
  56. name = c_name(prefix, protect=False) + 'qmp_schema_json'
  57. self.decl = mcgen('''
  58. extern const char %(c_name)s[];
  59. ''',
  60. c_name=c_name(name))
  61. lines = to_json(jsons).split('\n')
  62. c_string = '\n '.join([to_c_string(line) for line in lines])
  63. self.defn = mcgen('''
  64. const char %(c_name)s[] = %(c_string)s;
  65. ''',
  66. c_name=c_name(name),
  67. c_string=c_string)
  68. self._schema = None
  69. self._jsons = None
  70. self._used_types = None
  71. self._name_map = None
  72. def visit_needed(self, entity):
  73. # Ignore types on first pass; visit_end() will pick up used types
  74. return not isinstance(entity, QAPISchemaType)
  75. def _name(self, name):
  76. if self._unmask:
  77. return name
  78. if name not in self._name_map:
  79. self._name_map[name] = '%d' % len(self._name_map)
  80. return self._name_map[name]
  81. def _use_type(self, typ):
  82. # Map the various integer types to plain int
  83. if typ.json_type() == 'int':
  84. typ = self._schema.lookup_type('int')
  85. elif (isinstance(typ, QAPISchemaArrayType) and
  86. typ.element_type.json_type() == 'int'):
  87. typ = self._schema.lookup_type('intList')
  88. # Add type to work queue if new
  89. if typ not in self._used_types:
  90. self._used_types.append(typ)
  91. # Clients should examine commands and events, not types. Hide
  92. # type names to reduce the temptation. Also saves a few
  93. # characters.
  94. if isinstance(typ, QAPISchemaBuiltinType):
  95. return typ.name
  96. if isinstance(typ, QAPISchemaArrayType):
  97. return '[' + self._use_type(typ.element_type) + ']'
  98. return self._name(typ.name)
  99. def _gen_json(self, name, mtype, obj):
  100. if mtype not in ('command', 'event', 'builtin', 'array'):
  101. name = self._name(name)
  102. obj['name'] = name
  103. obj['meta-type'] = mtype
  104. self._jsons.append(obj)
  105. def _gen_member(self, member):
  106. ret = {'name': member.name, 'type': self._use_type(member.type)}
  107. if member.optional:
  108. ret['default'] = None
  109. return ret
  110. def _gen_variants(self, tag_name, variants):
  111. return {'tag': tag_name,
  112. 'variants': [self._gen_variant(v) for v in variants]}
  113. def _gen_variant(self, variant):
  114. return {'case': variant.name, 'type': self._use_type(variant.type)}
  115. def visit_builtin_type(self, name, info, json_type):
  116. self._gen_json(name, 'builtin', {'json-type': json_type})
  117. def visit_enum_type(self, name, info, values, prefix):
  118. self._gen_json(name, 'enum', {'values': values})
  119. def visit_array_type(self, name, info, element_type):
  120. element = self._use_type(element_type)
  121. self._gen_json('[' + element + ']', 'array', {'element-type': element})
  122. def visit_object_type_flat(self, name, info, members, variants):
  123. obj = {'members': [self._gen_member(m) for m in members]}
  124. if variants:
  125. obj.update(self._gen_variants(variants.tag_member.name,
  126. variants.variants))
  127. self._gen_json(name, 'object', obj)
  128. def visit_alternate_type(self, name, info, variants):
  129. self._gen_json(name, 'alternate',
  130. {'members': [{'type': self._use_type(m.type)}
  131. for m in variants.variants]})
  132. def visit_command(self, name, info, arg_type, ret_type,
  133. gen, success_response, boxed):
  134. arg_type = arg_type or self._schema.the_empty_object_type
  135. ret_type = ret_type or self._schema.the_empty_object_type
  136. self._gen_json(name, 'command',
  137. {'arg-type': self._use_type(arg_type),
  138. 'ret-type': self._use_type(ret_type)})
  139. def visit_event(self, name, info, arg_type, boxed):
  140. arg_type = arg_type or self._schema.the_empty_object_type
  141. self._gen_json(name, 'event', {'arg-type': self._use_type(arg_type)})
  142. # Debugging aid: unmask QAPI schema's type names
  143. # We normally mask them, because they're not QMP wire ABI
  144. opt_unmask = False
  145. (input_file, output_dir, do_c, do_h, prefix, opts) = \
  146. parse_command_line('u', ['unmask-non-abi-names'])
  147. for o, a in opts:
  148. if o in ('-u', '--unmask-non-abi-names'):
  149. opt_unmask = True
  150. blurb = ' * QAPI/QMP schema introspection'
  151. (fdef, fdecl) = open_output(output_dir, do_c, do_h, prefix,
  152. 'qmp-introspect.c', 'qmp-introspect.h',
  153. blurb, __doc__)
  154. fdef.write(mcgen('''
  155. #include "qemu/osdep.h"
  156. #include "%(prefix)sqmp-introspect.h"
  157. ''',
  158. prefix=prefix))
  159. schema = QAPISchema(input_file)
  160. gen = QAPISchemaGenIntrospectVisitor(opt_unmask)
  161. schema.visit(gen)
  162. fdef.write(gen.defn)
  163. fdecl.write(gen.decl)
  164. close_output(fdef, fdecl)