qapi-introspect.py 7.1 KB

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