2
0

introspect.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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 typing import (
  10. Any,
  11. Dict,
  12. Generic,
  13. Iterable,
  14. List,
  15. Optional,
  16. Tuple,
  17. TypeVar,
  18. Union,
  19. )
  20. from .common import (
  21. c_name,
  22. gen_endif,
  23. gen_if,
  24. mcgen,
  25. )
  26. from .gen import QAPISchemaMonolithicCVisitor
  27. from .schema import (
  28. QAPISchemaArrayType,
  29. QAPISchemaBuiltinType,
  30. QAPISchemaType,
  31. )
  32. # This module constructs a tree data structure that is used to
  33. # generate the introspection information for QEMU. It is shaped
  34. # like a JSON value.
  35. #
  36. # A complexity over JSON is that our values may or may not be annotated.
  37. #
  38. # Un-annotated values may be:
  39. # Scalar: str, bool, None.
  40. # Non-scalar: List, Dict
  41. # _value = Union[str, bool, None, Dict[str, JSONValue], List[JSONValue]]
  42. #
  43. # With optional annotations, the type of all values is:
  44. # JSONValue = Union[_Value, Annotated[_Value]]
  45. #
  46. # Sadly, mypy does not support recursive types; so the _Stub alias is used to
  47. # mark the imprecision in the type model where we'd otherwise use JSONValue.
  48. _Stub = Any
  49. _Scalar = Union[str, bool, None]
  50. _NonScalar = Union[Dict[str, _Stub], List[_Stub]]
  51. _Value = Union[_Scalar, _NonScalar]
  52. JSONValue = Union[_Value, 'Annotated[_Value]']
  53. _ValueT = TypeVar('_ValueT', bound=_Value)
  54. class Annotated(Generic[_ValueT]):
  55. """
  56. Annotated generally contains a SchemaInfo-like type (as a dict),
  57. But it also used to wrap comments/ifconds around scalar leaf values,
  58. for the benefit of features and enums.
  59. """
  60. # TODO: Remove after Python 3.7 adds @dataclass:
  61. # pylint: disable=too-few-public-methods
  62. def __init__(self, value: _ValueT, ifcond: Iterable[str],
  63. comment: Optional[str] = None):
  64. self.value = value
  65. self.comment: Optional[str] = comment
  66. self.ifcond: Tuple[str, ...] = tuple(ifcond)
  67. def _tree_to_qlit(obj, level=0, dict_value=False):
  68. def indent(level):
  69. return level * 4 * ' '
  70. if isinstance(obj, Annotated):
  71. # NB: _tree_to_qlit is called recursively on the values of a
  72. # key:value pair; those values can't be decorated with
  73. # comments or conditionals.
  74. msg = "dict values cannot have attached comments or if-conditionals."
  75. assert not dict_value, msg
  76. ret = ''
  77. if obj.comment:
  78. ret += indent(level) + f"/* {obj.comment} */\n"
  79. if obj.ifcond:
  80. ret += gen_if(obj.ifcond)
  81. ret += _tree_to_qlit(obj.value, level)
  82. if obj.ifcond:
  83. ret += '\n' + gen_endif(obj.ifcond)
  84. return ret
  85. ret = ''
  86. if not dict_value:
  87. ret += indent(level)
  88. # Scalars:
  89. if obj is None:
  90. ret += 'QLIT_QNULL'
  91. elif isinstance(obj, str):
  92. ret += f"QLIT_QSTR({to_c_string(obj)})"
  93. elif isinstance(obj, bool):
  94. ret += f"QLIT_QBOOL({str(obj).lower()})"
  95. # Non-scalars:
  96. elif isinstance(obj, list):
  97. ret += 'QLIT_QLIST(((QLitObject[]) {\n'
  98. for value in obj:
  99. ret += _tree_to_qlit(value, level + 1).strip('\n') + '\n'
  100. ret += indent(level + 1) + '{}\n'
  101. ret += indent(level) + '}))'
  102. elif isinstance(obj, dict):
  103. ret += 'QLIT_QDICT(((QLitDictEntry[]) {\n'
  104. for key, value in sorted(obj.items()):
  105. ret += indent(level + 1) + "{{ {:s}, {:s} }},\n".format(
  106. to_c_string(key),
  107. _tree_to_qlit(value, level + 1, dict_value=True)
  108. )
  109. ret += indent(level + 1) + '{}\n'
  110. ret += indent(level) + '}))'
  111. else:
  112. raise NotImplementedError(
  113. f"type '{type(obj).__name__}' not implemented"
  114. )
  115. if level > 0:
  116. ret += ','
  117. return ret
  118. def to_c_string(string):
  119. return '"' + string.replace('\\', r'\\').replace('"', r'\"') + '"'
  120. class QAPISchemaGenIntrospectVisitor(QAPISchemaMonolithicCVisitor):
  121. def __init__(self, prefix, unmask):
  122. super().__init__(
  123. prefix, 'qapi-introspect',
  124. ' * QAPI/QMP schema introspection', __doc__)
  125. self._unmask = unmask
  126. self._schema = None
  127. self._trees = []
  128. self._used_types = []
  129. self._name_map = {}
  130. self._genc.add(mcgen('''
  131. #include "qemu/osdep.h"
  132. #include "%(prefix)sqapi-introspect.h"
  133. ''',
  134. prefix=prefix))
  135. def visit_begin(self, schema):
  136. self._schema = schema
  137. def visit_end(self):
  138. # visit the types that are actually used
  139. for typ in self._used_types:
  140. typ.visit(self)
  141. # generate C
  142. name = c_name(self._prefix, protect=False) + 'qmp_schema_qlit'
  143. self._genh.add(mcgen('''
  144. #include "qapi/qmp/qlit.h"
  145. extern const QLitObject %(c_name)s;
  146. ''',
  147. c_name=c_name(name)))
  148. self._genc.add(mcgen('''
  149. const QLitObject %(c_name)s = %(c_string)s;
  150. ''',
  151. c_name=c_name(name),
  152. c_string=_tree_to_qlit(self._trees)))
  153. self._schema = None
  154. self._trees = []
  155. self._used_types = []
  156. self._name_map = {}
  157. def visit_needed(self, entity):
  158. # Ignore types on first pass; visit_end() will pick up used types
  159. return not isinstance(entity, QAPISchemaType)
  160. def _name(self, name):
  161. if self._unmask:
  162. return name
  163. if name not in self._name_map:
  164. self._name_map[name] = '%d' % len(self._name_map)
  165. return self._name_map[name]
  166. def _use_type(self, typ):
  167. assert self._schema is not None
  168. # Map the various integer types to plain int
  169. if typ.json_type() == 'int':
  170. typ = self._schema.lookup_type('int')
  171. elif (isinstance(typ, QAPISchemaArrayType) and
  172. typ.element_type.json_type() == 'int'):
  173. typ = self._schema.lookup_type('intList')
  174. # Add type to work queue if new
  175. if typ not in self._used_types:
  176. self._used_types.append(typ)
  177. # Clients should examine commands and events, not types. Hide
  178. # type names as integers to reduce the temptation. Also, it
  179. # saves a few characters on the wire.
  180. if isinstance(typ, QAPISchemaBuiltinType):
  181. return typ.name
  182. if isinstance(typ, QAPISchemaArrayType):
  183. return '[' + self._use_type(typ.element_type) + ']'
  184. return self._name(typ.name)
  185. @staticmethod
  186. def _gen_features(features):
  187. return [Annotated(f.name, f.ifcond) for f in features]
  188. def _gen_tree(self, name, mtype, obj, ifcond, features):
  189. comment: Optional[str] = None
  190. if mtype not in ('command', 'event', 'builtin', 'array'):
  191. if not self._unmask:
  192. # Output a comment to make it easy to map masked names
  193. # back to the source when reading the generated output.
  194. comment = f'"{self._name(name)}" = {name}'
  195. name = self._name(name)
  196. obj['name'] = name
  197. obj['meta-type'] = mtype
  198. if features:
  199. obj['features'] = self._gen_features(features)
  200. self._trees.append(Annotated(obj, ifcond, comment))
  201. def _gen_member(self, member):
  202. obj = {'name': member.name, 'type': self._use_type(member.type)}
  203. if member.optional:
  204. obj['default'] = None
  205. if member.features:
  206. obj['features'] = self._gen_features(member.features)
  207. return Annotated(obj, member.ifcond)
  208. def _gen_variant(self, variant):
  209. obj = {'case': variant.name, 'type': self._use_type(variant.type)}
  210. return Annotated(obj, variant.ifcond)
  211. def visit_builtin_type(self, name, info, json_type):
  212. self._gen_tree(name, 'builtin', {'json-type': json_type}, [], None)
  213. def visit_enum_type(self, name, info, ifcond, features, members, prefix):
  214. self._gen_tree(
  215. name, 'enum',
  216. {'values': [Annotated(m.name, m.ifcond) for m in members]},
  217. ifcond, features
  218. )
  219. def visit_array_type(self, name, info, ifcond, element_type):
  220. element = self._use_type(element_type)
  221. self._gen_tree('[' + element + ']', 'array', {'element-type': element},
  222. ifcond, None)
  223. def visit_object_type_flat(self, name, info, ifcond, features,
  224. members, variants):
  225. obj = {'members': [self._gen_member(m) for m in members]}
  226. if variants:
  227. obj['tag'] = variants.tag_member.name
  228. obj['variants'] = [self._gen_variant(v) for v in variants.variants]
  229. self._gen_tree(name, 'object', obj, ifcond, features)
  230. def visit_alternate_type(self, name, info, ifcond, features, variants):
  231. self._gen_tree(
  232. name, 'alternate',
  233. {'members': [Annotated({'type': self._use_type(m.type)},
  234. m.ifcond)
  235. for m in variants.variants]},
  236. ifcond, features
  237. )
  238. def visit_command(self, name, info, ifcond, features,
  239. arg_type, ret_type, gen, success_response, boxed,
  240. allow_oob, allow_preconfig, coroutine):
  241. assert self._schema is not None
  242. arg_type = arg_type or self._schema.the_empty_object_type
  243. ret_type = ret_type or self._schema.the_empty_object_type
  244. obj = {'arg-type': self._use_type(arg_type),
  245. 'ret-type': self._use_type(ret_type)}
  246. if allow_oob:
  247. obj['allow-oob'] = allow_oob
  248. self._gen_tree(name, 'command', obj, ifcond, features)
  249. def visit_event(self, name, info, ifcond, features, arg_type, boxed):
  250. assert self._schema is not None
  251. arg_type = arg_type or self._schema.the_empty_object_type
  252. self._gen_tree(name, 'event', {'arg-type': self._use_type(arg_type)},
  253. ifcond, features)
  254. def gen_introspect(schema, output_dir, prefix, opt_unmask):
  255. vis = QAPISchemaGenIntrospectVisitor(prefix, opt_unmask)
  256. schema.visit(vis)
  257. vis.write(output_dir)