2
0

introspect.py 13 KB

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