introspect.py 14 KB

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