introspect.py 14 KB

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