introspect.py 14 KB

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