introspect.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. """
  2. QAPI introspection generator
  3. Copyright (C) 2015-2021 Red Hat, Inc.
  4. Authors:
  5. Markus Armbruster <armbru@redhat.com>
  6. John Snow <jsnow@redhat.com>
  7. This work is licensed under the terms of the GNU GPL, version 2.
  8. See the COPYING file in the top-level directory.
  9. """
  10. from typing import (
  11. Any,
  12. Dict,
  13. Generic,
  14. List,
  15. Optional,
  16. Sequence,
  17. TypeVar,
  18. Union,
  19. )
  20. from .common import c_name, mcgen
  21. from .gen import QAPISchemaMonolithicCVisitor
  22. from .schema import (
  23. QAPISchema,
  24. QAPISchemaArrayType,
  25. QAPISchemaBuiltinType,
  26. QAPISchemaEntity,
  27. QAPISchemaEnumMember,
  28. QAPISchemaFeature,
  29. QAPISchemaIfCond,
  30. QAPISchemaObjectType,
  31. QAPISchemaObjectTypeMember,
  32. QAPISchemaType,
  33. QAPISchemaVariant,
  34. QAPISchemaVariants,
  35. )
  36. from .source import QAPISourceInfo
  37. # This module constructs a tree data structure that is used to
  38. # generate the introspection information for QEMU. It is shaped
  39. # like a JSON value.
  40. #
  41. # A complexity over JSON is that our values may or may not be annotated.
  42. #
  43. # Un-annotated values may be:
  44. # Scalar: str, bool, None.
  45. # Non-scalar: List, Dict
  46. # _value = Union[str, bool, None, Dict[str, JSONValue], List[JSONValue]]
  47. #
  48. # With optional annotations, the type of all values is:
  49. # JSONValue = Union[_Value, Annotated[_Value]]
  50. #
  51. # Sadly, mypy does not support recursive types; so the _Stub alias is used to
  52. # mark the imprecision in the type model where we'd otherwise use JSONValue.
  53. _Stub = Any
  54. _Scalar = Union[str, bool, None]
  55. _NonScalar = Union[Dict[str, _Stub], List[_Stub]]
  56. _Value = Union[_Scalar, _NonScalar]
  57. JSONValue = Union[_Value, 'Annotated[_Value]']
  58. # These types are based on structures defined in QEMU's schema, so we
  59. # lack precise types for them here. Python 3.6 does not offer
  60. # TypedDict constructs, so they are broadly typed here as simple
  61. # Python Dicts.
  62. SchemaInfo = Dict[str, object]
  63. SchemaInfoEnumMember = Dict[str, object]
  64. SchemaInfoObject = Dict[str, object]
  65. SchemaInfoObjectVariant = Dict[str, object]
  66. SchemaInfoObjectMember = Dict[str, object]
  67. SchemaInfoCommand = Dict[str, object]
  68. _ValueT = TypeVar('_ValueT', bound=_Value)
  69. class Annotated(Generic[_ValueT]):
  70. """
  71. Annotated generally contains a SchemaInfo-like type (as a dict),
  72. But it also used to wrap comments/ifconds around scalar leaf values,
  73. for the benefit of features and enums.
  74. """
  75. # TODO: Remove after Python 3.7 adds @dataclass:
  76. # pylint: disable=too-few-public-methods
  77. def __init__(self, value: _ValueT, ifcond: QAPISchemaIfCond,
  78. comment: Optional[str] = None):
  79. self.value = value
  80. self.comment: Optional[str] = comment
  81. self.ifcond = ifcond
  82. def _tree_to_qlit(obj: JSONValue,
  83. level: int = 0,
  84. dict_value: bool = False) -> str:
  85. """
  86. Convert the type tree into a QLIT C string, recursively.
  87. :param obj: The value to convert.
  88. This value may not be Annotated when dict_value is True.
  89. :param level: The indentation level for this particular value.
  90. :param dict_value: True when the value being processed belongs to a
  91. dict key; which suppresses the output indent.
  92. """
  93. def indent(level: int) -> str:
  94. return level * 4 * ' '
  95. if isinstance(obj, Annotated):
  96. # NB: _tree_to_qlit is called recursively on the values of a
  97. # key:value pair; those values can't be decorated with
  98. # comments or conditionals.
  99. msg = "dict values cannot have attached comments or if-conditionals."
  100. assert not dict_value, msg
  101. ret = ''
  102. if obj.comment:
  103. ret += indent(level) + f"/* {obj.comment} */\n"
  104. if obj.ifcond.is_present():
  105. ret += obj.ifcond.gen_if()
  106. ret += _tree_to_qlit(obj.value, level)
  107. if obj.ifcond.is_present():
  108. ret += '\n' + obj.ifcond.gen_endif()
  109. return ret
  110. ret = ''
  111. if not dict_value:
  112. ret += indent(level)
  113. # Scalars:
  114. if obj is None:
  115. ret += 'QLIT_QNULL'
  116. elif isinstance(obj, str):
  117. ret += f"QLIT_QSTR({to_c_string(obj)})"
  118. elif isinstance(obj, bool):
  119. ret += f"QLIT_QBOOL({str(obj).lower()})"
  120. # Non-scalars:
  121. elif isinstance(obj, list):
  122. ret += 'QLIT_QLIST(((QLitObject[]) {\n'
  123. for value in obj:
  124. ret += _tree_to_qlit(value, level + 1).strip('\n') + '\n'
  125. ret += indent(level + 1) + '{}\n'
  126. ret += indent(level) + '}))'
  127. elif isinstance(obj, dict):
  128. ret += 'QLIT_QDICT(((QLitDictEntry[]) {\n'
  129. for key, value in sorted(obj.items()):
  130. ret += indent(level + 1) + "{{ {:s}, {:s} }},\n".format(
  131. to_c_string(key),
  132. _tree_to_qlit(value, level + 1, dict_value=True)
  133. )
  134. ret += indent(level + 1) + '{}\n'
  135. ret += indent(level) + '}))'
  136. else:
  137. raise NotImplementedError(
  138. f"type '{type(obj).__name__}' not implemented"
  139. )
  140. if level > 0:
  141. ret += ','
  142. return ret
  143. def to_c_string(string: str) -> str:
  144. return '"' + string.replace('\\', r'\\').replace('"', r'\"') + '"'
  145. class QAPISchemaGenIntrospectVisitor(QAPISchemaMonolithicCVisitor):
  146. def __init__(self, prefix: str, unmask: bool):
  147. super().__init__(
  148. prefix, 'qapi-introspect',
  149. ' * QAPI/QMP schema introspection', __doc__)
  150. self._unmask = unmask
  151. self._schema: Optional[QAPISchema] = None
  152. self._trees: List[Annotated[SchemaInfo]] = []
  153. self._used_types: List[QAPISchemaType] = []
  154. self._name_map: Dict[str, str] = {}
  155. self._genc.add(mcgen('''
  156. #include "qemu/osdep.h"
  157. #include "%(prefix)sqapi-introspect.h"
  158. ''',
  159. prefix=prefix))
  160. def visit_begin(self, schema: QAPISchema) -> None:
  161. self._schema = schema
  162. def visit_end(self) -> None:
  163. # visit the types that are actually used
  164. for typ in self._used_types:
  165. typ.visit(self)
  166. # generate C
  167. name = c_name(self._prefix, protect=False) + 'qmp_schema_qlit'
  168. self._genh.add(mcgen('''
  169. #include "qapi/qmp/qlit.h"
  170. extern const QLitObject %(c_name)s;
  171. ''',
  172. c_name=c_name(name)))
  173. self._genc.add(mcgen('''
  174. const QLitObject %(c_name)s = %(c_string)s;
  175. ''',
  176. c_name=c_name(name),
  177. c_string=_tree_to_qlit(self._trees)))
  178. self._schema = None
  179. self._trees = []
  180. self._used_types = []
  181. self._name_map = {}
  182. def visit_needed(self, entity: QAPISchemaEntity) -> bool:
  183. # Ignore types on first pass; visit_end() will pick up used types
  184. return not isinstance(entity, QAPISchemaType)
  185. def _name(self, name: str) -> str:
  186. if self._unmask:
  187. return name
  188. if name not in self._name_map:
  189. self._name_map[name] = '%d' % len(self._name_map)
  190. return self._name_map[name]
  191. def _use_type(self, typ: QAPISchemaType) -> str:
  192. assert self._schema is not None
  193. # Map the various integer types to plain int
  194. if typ.json_type() == 'int':
  195. typ = self._schema.lookup_type('int')
  196. elif (isinstance(typ, QAPISchemaArrayType) and
  197. typ.element_type.json_type() == 'int'):
  198. typ = self._schema.lookup_type('intList')
  199. # Add type to work queue if new
  200. if typ not in self._used_types:
  201. self._used_types.append(typ)
  202. # Clients should examine commands and events, not types. Hide
  203. # type names as integers to reduce the temptation. Also, it
  204. # saves a few characters on the wire.
  205. if isinstance(typ, QAPISchemaBuiltinType):
  206. return typ.name
  207. if isinstance(typ, QAPISchemaArrayType):
  208. return '[' + self._use_type(typ.element_type) + ']'
  209. return self._name(typ.name)
  210. @staticmethod
  211. def _gen_features(features: Sequence[QAPISchemaFeature]
  212. ) -> List[Annotated[str]]:
  213. return [Annotated(f.name, f.ifcond) for f in features]
  214. def _gen_tree(self, name: str, mtype: str, obj: Dict[str, object],
  215. ifcond: QAPISchemaIfCond = QAPISchemaIfCond(),
  216. features: Sequence[QAPISchemaFeature] = ()) -> None:
  217. """
  218. Build and append a SchemaInfo object to self._trees.
  219. :param name: The SchemaInfo's name.
  220. :param mtype: The SchemaInfo's meta-type.
  221. :param obj: Additional SchemaInfo members, as appropriate for
  222. the meta-type.
  223. :param ifcond: Conditionals to apply to the SchemaInfo.
  224. :param features: The SchemaInfo's features.
  225. Will be omitted from the output if empty.
  226. """
  227. comment: Optional[str] = None
  228. if mtype not in ('command', 'event', 'builtin', 'array'):
  229. if not self._unmask:
  230. # Output a comment to make it easy to map masked names
  231. # back to the source when reading the generated output.
  232. comment = f'"{self._name(name)}" = {name}'
  233. name = self._name(name)
  234. obj['name'] = name
  235. obj['meta-type'] = mtype
  236. if features:
  237. obj['features'] = self._gen_features(features)
  238. self._trees.append(Annotated(obj, ifcond, comment))
  239. @staticmethod
  240. def _gen_enum_member(member: QAPISchemaEnumMember
  241. ) -> Annotated[SchemaInfoEnumMember]:
  242. obj: SchemaInfoEnumMember = {
  243. 'name': member.name,
  244. }
  245. return Annotated(obj, member.ifcond)
  246. def _gen_object_member(self, member: QAPISchemaObjectTypeMember
  247. ) -> Annotated[SchemaInfoObjectMember]:
  248. obj: SchemaInfoObjectMember = {
  249. 'name': member.name,
  250. 'type': self._use_type(member.type)
  251. }
  252. if member.optional:
  253. obj['default'] = None
  254. if member.features:
  255. obj['features'] = self._gen_features(member.features)
  256. return Annotated(obj, member.ifcond)
  257. def _gen_variant(self, variant: QAPISchemaVariant
  258. ) -> Annotated[SchemaInfoObjectVariant]:
  259. obj: SchemaInfoObjectVariant = {
  260. 'case': variant.name,
  261. 'type': self._use_type(variant.type)
  262. }
  263. return Annotated(obj, variant.ifcond)
  264. def visit_builtin_type(self, name: str, info: Optional[QAPISourceInfo],
  265. json_type: str) -> None:
  266. self._gen_tree(name, 'builtin', {'json-type': json_type})
  267. def visit_enum_type(self, name: str, info: Optional[QAPISourceInfo],
  268. ifcond: QAPISchemaIfCond,
  269. features: List[QAPISchemaFeature],
  270. members: List[QAPISchemaEnumMember],
  271. prefix: Optional[str]) -> None:
  272. self._gen_tree(
  273. name, 'enum',
  274. {'members': [self._gen_enum_member(m) for m in members],
  275. 'values': [Annotated(m.name, m.ifcond) for m in members]},
  276. ifcond, features
  277. )
  278. def visit_array_type(self, name: str, info: Optional[QAPISourceInfo],
  279. ifcond: QAPISchemaIfCond,
  280. element_type: QAPISchemaType) -> None:
  281. element = self._use_type(element_type)
  282. self._gen_tree('[' + element + ']', 'array', {'element-type': element},
  283. ifcond)
  284. def visit_object_type_flat(self, name: str, info: Optional[QAPISourceInfo],
  285. ifcond: QAPISchemaIfCond,
  286. features: List[QAPISchemaFeature],
  287. members: List[QAPISchemaObjectTypeMember],
  288. variants: Optional[QAPISchemaVariants]) -> None:
  289. obj: SchemaInfoObject = {
  290. 'members': [self._gen_object_member(m) for m in members]
  291. }
  292. if variants:
  293. obj['tag'] = variants.tag_member.name
  294. obj['variants'] = [self._gen_variant(v) for v in variants.variants]
  295. self._gen_tree(name, 'object', obj, ifcond, features)
  296. def visit_alternate_type(self, name: str, info: Optional[QAPISourceInfo],
  297. ifcond: QAPISchemaIfCond,
  298. features: List[QAPISchemaFeature],
  299. variants: QAPISchemaVariants) -> None:
  300. self._gen_tree(
  301. name, 'alternate',
  302. {'members': [Annotated({'type': self._use_type(m.type)},
  303. m.ifcond)
  304. for m in variants.variants]},
  305. ifcond, features
  306. )
  307. def visit_command(self, name: str, info: Optional[QAPISourceInfo],
  308. ifcond: QAPISchemaIfCond,
  309. features: List[QAPISchemaFeature],
  310. arg_type: Optional[QAPISchemaObjectType],
  311. ret_type: Optional[QAPISchemaType], gen: bool,
  312. success_response: bool, boxed: bool, allow_oob: bool,
  313. allow_preconfig: bool, coroutine: bool) -> None:
  314. assert self._schema is not None
  315. arg_type = arg_type or self._schema.the_empty_object_type
  316. ret_type = ret_type or self._schema.the_empty_object_type
  317. obj: SchemaInfoCommand = {
  318. 'arg-type': self._use_type(arg_type),
  319. 'ret-type': self._use_type(ret_type)
  320. }
  321. if allow_oob:
  322. obj['allow-oob'] = allow_oob
  323. self._gen_tree(name, 'command', obj, ifcond, features)
  324. def visit_event(self, name: str, info: Optional[QAPISourceInfo],
  325. ifcond: QAPISchemaIfCond,
  326. features: List[QAPISchemaFeature],
  327. arg_type: Optional[QAPISchemaObjectType],
  328. boxed: bool) -> None:
  329. assert self._schema is not None
  330. arg_type = arg_type or self._schema.the_empty_object_type
  331. self._gen_tree(name, 'event', {'arg-type': self._use_type(arg_type)},
  332. ifcond, features)
  333. def gen_introspect(schema: QAPISchema, output_dir: str, prefix: str,
  334. opt_unmask: bool) -> None:
  335. vis = QAPISchemaGenIntrospectVisitor(prefix, opt_unmask)
  336. schema.visit(vis)
  337. vis.write(output_dir)