schema.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  1. # -*- coding: utf-8 -*-
  2. #
  3. # QAPI schema internal representation
  4. #
  5. # Copyright (c) 2015-2019 Red Hat Inc.
  6. #
  7. # Authors:
  8. # Markus Armbruster <armbru@redhat.com>
  9. # Eric Blake <eblake@redhat.com>
  10. # Marc-André Lureau <marcandre.lureau@redhat.com>
  11. #
  12. # This work is licensed under the terms of the GNU GPL, version 2.
  13. # See the COPYING file in the top-level directory.
  14. # pylint: disable=too-many-lines
  15. # TODO catching name collisions in generated code would be nice
  16. from __future__ import annotations
  17. from abc import ABC, abstractmethod
  18. from collections import OrderedDict
  19. import os
  20. import re
  21. from typing import (
  22. Any,
  23. Callable,
  24. Dict,
  25. List,
  26. Optional,
  27. Union,
  28. cast,
  29. )
  30. from .common import (
  31. POINTER_SUFFIX,
  32. c_name,
  33. cgen_ifcond,
  34. docgen_ifcond,
  35. gen_endif,
  36. gen_if,
  37. )
  38. from .error import QAPIError, QAPISemError, QAPISourceError
  39. from .expr import check_exprs
  40. from .parser import QAPIDoc, QAPIExpression, QAPISchemaParser
  41. from .source import QAPISourceInfo
  42. class QAPISchemaIfCond:
  43. def __init__(
  44. self,
  45. ifcond: Optional[Union[str, Dict[str, object]]] = None,
  46. ) -> None:
  47. self.ifcond = ifcond
  48. def _cgen(self) -> str:
  49. return cgen_ifcond(self.ifcond)
  50. def gen_if(self) -> str:
  51. return gen_if(self._cgen())
  52. def gen_endif(self) -> str:
  53. return gen_endif(self._cgen())
  54. def docgen(self) -> str:
  55. return docgen_ifcond(self.ifcond)
  56. def is_present(self) -> bool:
  57. return bool(self.ifcond)
  58. class QAPISchemaEntity:
  59. """
  60. A schema entity.
  61. This is either a directive, such as include, or a definition.
  62. The latter uses sub-class `QAPISchemaDefinition`.
  63. """
  64. def __init__(self, info: Optional[QAPISourceInfo]):
  65. self._module: Optional[QAPISchemaModule] = None
  66. # For explicitly defined entities, info points to the (explicit)
  67. # definition. For builtins (and their arrays), info is None.
  68. # For implicitly defined entities, info points to a place that
  69. # triggered the implicit definition (there may be more than one
  70. # such place).
  71. self.info = info
  72. self._checked = False
  73. def __repr__(self) -> str:
  74. return "<%s at 0x%x>" % (type(self).__name__, id(self))
  75. def check(self, schema: QAPISchema) -> None:
  76. # pylint: disable=unused-argument
  77. self._checked = True
  78. def connect_doc(self, doc: Optional[QAPIDoc] = None) -> None:
  79. pass
  80. def _set_module(
  81. self, schema: QAPISchema, info: Optional[QAPISourceInfo]
  82. ) -> None:
  83. assert self._checked
  84. fname = info.fname if info else QAPISchemaModule.BUILTIN_MODULE_NAME
  85. self._module = schema.module_by_fname(fname)
  86. self._module.add_entity(self)
  87. def set_module(self, schema: QAPISchema) -> None:
  88. self._set_module(schema, self.info)
  89. def visit(self, visitor: QAPISchemaVisitor) -> None:
  90. # pylint: disable=unused-argument
  91. assert self._checked
  92. class QAPISchemaDefinition(QAPISchemaEntity):
  93. meta: str
  94. def __init__(
  95. self,
  96. name: str,
  97. info: Optional[QAPISourceInfo],
  98. doc: Optional[QAPIDoc],
  99. ifcond: Optional[QAPISchemaIfCond] = None,
  100. features: Optional[List[QAPISchemaFeature]] = None,
  101. ):
  102. super().__init__(info)
  103. for f in features or []:
  104. f.set_defined_in(name)
  105. self.name = name
  106. self.doc = doc
  107. self._ifcond = ifcond or QAPISchemaIfCond()
  108. self.features = features or []
  109. def __repr__(self) -> str:
  110. return "<%s:%s at 0x%x>" % (type(self).__name__, self.name,
  111. id(self))
  112. def c_name(self) -> str:
  113. return c_name(self.name)
  114. def check(self, schema: QAPISchema) -> None:
  115. assert not self._checked
  116. super().check(schema)
  117. seen: Dict[str, QAPISchemaMember] = {}
  118. for f in self.features:
  119. f.check_clash(self.info, seen)
  120. def connect_doc(self, doc: Optional[QAPIDoc] = None) -> None:
  121. super().connect_doc(doc)
  122. doc = doc or self.doc
  123. if doc:
  124. for f in self.features:
  125. doc.connect_feature(f)
  126. @property
  127. def ifcond(self) -> QAPISchemaIfCond:
  128. assert self._checked
  129. return self._ifcond
  130. def is_implicit(self) -> bool:
  131. return not self.info
  132. def describe(self) -> str:
  133. return "%s '%s'" % (self.meta, self.name)
  134. class QAPISchemaVisitor:
  135. def visit_begin(self, schema: QAPISchema) -> None:
  136. pass
  137. def visit_end(self) -> None:
  138. pass
  139. def visit_module(self, name: str) -> None:
  140. pass
  141. def visit_needed(self, entity: QAPISchemaEntity) -> bool:
  142. # pylint: disable=unused-argument
  143. # Default to visiting everything
  144. return True
  145. def visit_include(self, name: str, info: Optional[QAPISourceInfo]) -> None:
  146. pass
  147. def visit_builtin_type(
  148. self, name: str, info: Optional[QAPISourceInfo], json_type: str
  149. ) -> None:
  150. pass
  151. def visit_enum_type(
  152. self,
  153. name: str,
  154. info: Optional[QAPISourceInfo],
  155. ifcond: QAPISchemaIfCond,
  156. features: List[QAPISchemaFeature],
  157. members: List[QAPISchemaEnumMember],
  158. prefix: Optional[str],
  159. ) -> None:
  160. pass
  161. def visit_array_type(
  162. self,
  163. name: str,
  164. info: Optional[QAPISourceInfo],
  165. ifcond: QAPISchemaIfCond,
  166. element_type: QAPISchemaType,
  167. ) -> None:
  168. pass
  169. def visit_object_type(
  170. self,
  171. name: str,
  172. info: Optional[QAPISourceInfo],
  173. ifcond: QAPISchemaIfCond,
  174. features: List[QAPISchemaFeature],
  175. base: Optional[QAPISchemaObjectType],
  176. members: List[QAPISchemaObjectTypeMember],
  177. variants: Optional[QAPISchemaVariants],
  178. ) -> None:
  179. pass
  180. def visit_object_type_flat(
  181. self,
  182. name: str,
  183. info: Optional[QAPISourceInfo],
  184. ifcond: QAPISchemaIfCond,
  185. features: List[QAPISchemaFeature],
  186. members: List[QAPISchemaObjectTypeMember],
  187. variants: Optional[QAPISchemaVariants],
  188. ) -> None:
  189. pass
  190. def visit_alternate_type(
  191. self,
  192. name: str,
  193. info: Optional[QAPISourceInfo],
  194. ifcond: QAPISchemaIfCond,
  195. features: List[QAPISchemaFeature],
  196. variants: QAPISchemaVariants,
  197. ) -> None:
  198. pass
  199. def visit_command(
  200. self,
  201. name: str,
  202. info: Optional[QAPISourceInfo],
  203. ifcond: QAPISchemaIfCond,
  204. features: List[QAPISchemaFeature],
  205. arg_type: Optional[QAPISchemaObjectType],
  206. ret_type: Optional[QAPISchemaType],
  207. gen: bool,
  208. success_response: bool,
  209. boxed: bool,
  210. allow_oob: bool,
  211. allow_preconfig: bool,
  212. coroutine: bool,
  213. ) -> None:
  214. pass
  215. def visit_event(
  216. self,
  217. name: str,
  218. info: Optional[QAPISourceInfo],
  219. ifcond: QAPISchemaIfCond,
  220. features: List[QAPISchemaFeature],
  221. arg_type: Optional[QAPISchemaObjectType],
  222. boxed: bool,
  223. ) -> None:
  224. pass
  225. class QAPISchemaModule:
  226. BUILTIN_MODULE_NAME = './builtin'
  227. def __init__(self, name: str):
  228. self.name = name
  229. self._entity_list: List[QAPISchemaEntity] = []
  230. @staticmethod
  231. def is_system_module(name: str) -> bool:
  232. """
  233. System modules are internally defined modules.
  234. Their names start with the "./" prefix.
  235. """
  236. return name.startswith('./')
  237. @classmethod
  238. def is_user_module(cls, name: str) -> bool:
  239. """
  240. User modules are those defined by the user in qapi JSON files.
  241. They do not start with the "./" prefix.
  242. """
  243. return not cls.is_system_module(name)
  244. @classmethod
  245. def is_builtin_module(cls, name: str) -> bool:
  246. """
  247. The built-in module is a single System module for the built-in types.
  248. It is always "./builtin".
  249. """
  250. return name == cls.BUILTIN_MODULE_NAME
  251. def add_entity(self, ent: QAPISchemaEntity) -> None:
  252. self._entity_list.append(ent)
  253. def visit(self, visitor: QAPISchemaVisitor) -> None:
  254. visitor.visit_module(self.name)
  255. for entity in self._entity_list:
  256. if visitor.visit_needed(entity):
  257. entity.visit(visitor)
  258. class QAPISchemaInclude(QAPISchemaEntity):
  259. def __init__(self, sub_module: QAPISchemaModule, info: QAPISourceInfo):
  260. super().__init__(info)
  261. self._sub_module = sub_module
  262. def visit(self, visitor: QAPISchemaVisitor) -> None:
  263. super().visit(visitor)
  264. visitor.visit_include(self._sub_module.name, self.info)
  265. class QAPISchemaType(QAPISchemaDefinition, ABC):
  266. # Return the C type for common use.
  267. # For the types we commonly box, this is a pointer type.
  268. @abstractmethod
  269. def c_type(self) -> str:
  270. pass
  271. # Return the C type to be used in a parameter list.
  272. def c_param_type(self) -> str:
  273. return self.c_type()
  274. # Return the C type to be used where we suppress boxing.
  275. def c_unboxed_type(self) -> str:
  276. return self.c_type()
  277. @abstractmethod
  278. def json_type(self) -> str:
  279. pass
  280. def alternate_qtype(self) -> Optional[str]:
  281. json2qtype = {
  282. 'null': 'QTYPE_QNULL',
  283. 'string': 'QTYPE_QSTRING',
  284. 'number': 'QTYPE_QNUM',
  285. 'int': 'QTYPE_QNUM',
  286. 'boolean': 'QTYPE_QBOOL',
  287. 'array': 'QTYPE_QLIST',
  288. 'object': 'QTYPE_QDICT'
  289. }
  290. return json2qtype.get(self.json_type())
  291. def doc_type(self) -> Optional[str]:
  292. if self.is_implicit():
  293. return None
  294. return self.name
  295. def need_has_if_optional(self) -> bool:
  296. # When FOO is a pointer, has_FOO == !!FOO, i.e. has_FOO is redundant.
  297. # Except for arrays; see QAPISchemaArrayType.need_has_if_optional().
  298. return not self.c_type().endswith(POINTER_SUFFIX)
  299. def check(self, schema: QAPISchema) -> None:
  300. super().check(schema)
  301. for feat in self.features:
  302. if feat.is_special():
  303. raise QAPISemError(
  304. self.info,
  305. f"feature '{feat.name}' is not supported for types")
  306. def describe(self) -> str:
  307. return "%s type '%s'" % (self.meta, self.name)
  308. class QAPISchemaBuiltinType(QAPISchemaType):
  309. meta = 'built-in'
  310. def __init__(self, name: str, json_type: str, c_type: str):
  311. super().__init__(name, None, None)
  312. assert json_type in ('string', 'number', 'int', 'boolean', 'null',
  313. 'value')
  314. self._json_type_name = json_type
  315. self._c_type_name = c_type
  316. def c_name(self) -> str:
  317. return self.name
  318. def c_type(self) -> str:
  319. return self._c_type_name
  320. def c_param_type(self) -> str:
  321. if self.name == 'str':
  322. return 'const ' + self._c_type_name
  323. return self._c_type_name
  324. def json_type(self) -> str:
  325. return self._json_type_name
  326. def doc_type(self) -> str:
  327. return self.json_type()
  328. def visit(self, visitor: QAPISchemaVisitor) -> None:
  329. super().visit(visitor)
  330. visitor.visit_builtin_type(self.name, self.info, self.json_type())
  331. class QAPISchemaEnumType(QAPISchemaType):
  332. meta = 'enum'
  333. def __init__(
  334. self,
  335. name: str,
  336. info: Optional[QAPISourceInfo],
  337. doc: Optional[QAPIDoc],
  338. ifcond: Optional[QAPISchemaIfCond],
  339. features: Optional[List[QAPISchemaFeature]],
  340. members: List[QAPISchemaEnumMember],
  341. prefix: Optional[str],
  342. ):
  343. super().__init__(name, info, doc, ifcond, features)
  344. for m in members:
  345. m.set_defined_in(name)
  346. self.members = members
  347. self.prefix = prefix
  348. def check(self, schema: QAPISchema) -> None:
  349. super().check(schema)
  350. seen: Dict[str, QAPISchemaMember] = {}
  351. for m in self.members:
  352. m.check_clash(self.info, seen)
  353. def connect_doc(self, doc: Optional[QAPIDoc] = None) -> None:
  354. super().connect_doc(doc)
  355. doc = doc or self.doc
  356. for m in self.members:
  357. m.connect_doc(doc)
  358. def is_implicit(self) -> bool:
  359. # See QAPISchema._def_predefineds()
  360. return self.name == 'QType'
  361. def c_type(self) -> str:
  362. return c_name(self.name)
  363. def member_names(self) -> List[str]:
  364. return [m.name for m in self.members]
  365. def json_type(self) -> str:
  366. return 'string'
  367. def visit(self, visitor: QAPISchemaVisitor) -> None:
  368. super().visit(visitor)
  369. visitor.visit_enum_type(
  370. self.name, self.info, self.ifcond, self.features,
  371. self.members, self.prefix)
  372. class QAPISchemaArrayType(QAPISchemaType):
  373. meta = 'array'
  374. def __init__(
  375. self, name: str, info: Optional[QAPISourceInfo], element_type: str
  376. ):
  377. super().__init__(name, info, None)
  378. self._element_type_name = element_type
  379. self.element_type: QAPISchemaType
  380. def need_has_if_optional(self) -> bool:
  381. # When FOO is an array, we still need has_FOO to distinguish
  382. # absent (!has_FOO) from present and empty (has_FOO && !FOO).
  383. return True
  384. def check(self, schema: QAPISchema) -> None:
  385. super().check(schema)
  386. self.element_type = schema.resolve_type(
  387. self._element_type_name, self.info,
  388. self.info.defn_meta if self.info else None)
  389. assert not isinstance(self.element_type, QAPISchemaArrayType)
  390. def set_module(self, schema: QAPISchema) -> None:
  391. self._set_module(schema, self.element_type.info)
  392. @property
  393. def ifcond(self) -> QAPISchemaIfCond:
  394. assert self._checked
  395. return self.element_type.ifcond
  396. def is_implicit(self) -> bool:
  397. return True
  398. def c_type(self) -> str:
  399. return c_name(self.name) + POINTER_SUFFIX
  400. def json_type(self) -> str:
  401. return 'array'
  402. def doc_type(self) -> Optional[str]:
  403. elt_doc_type = self.element_type.doc_type()
  404. if not elt_doc_type:
  405. return None
  406. return 'array of ' + elt_doc_type
  407. def visit(self, visitor: QAPISchemaVisitor) -> None:
  408. super().visit(visitor)
  409. visitor.visit_array_type(self.name, self.info, self.ifcond,
  410. self.element_type)
  411. def describe(self) -> str:
  412. return "%s type ['%s']" % (self.meta, self._element_type_name)
  413. class QAPISchemaObjectType(QAPISchemaType):
  414. def __init__(
  415. self,
  416. name: str,
  417. info: Optional[QAPISourceInfo],
  418. doc: Optional[QAPIDoc],
  419. ifcond: Optional[QAPISchemaIfCond],
  420. features: Optional[List[QAPISchemaFeature]],
  421. base: Optional[str],
  422. local_members: List[QAPISchemaObjectTypeMember],
  423. variants: Optional[QAPISchemaVariants],
  424. ):
  425. # struct has local_members, optional base, and no variants
  426. # union has base, variants, and no local_members
  427. super().__init__(name, info, doc, ifcond, features)
  428. self.meta = 'union' if variants else 'struct'
  429. for m in local_members:
  430. m.set_defined_in(name)
  431. if variants is not None:
  432. variants.set_defined_in(name)
  433. self._base_name = base
  434. self.base = None
  435. self.local_members = local_members
  436. self.variants = variants
  437. self.members: List[QAPISchemaObjectTypeMember]
  438. self._check_complete = False
  439. def check(self, schema: QAPISchema) -> None:
  440. # This calls another type T's .check() exactly when the C
  441. # struct emitted by gen_object() contains that T's C struct
  442. # (pointers don't count).
  443. if self._check_complete:
  444. # A previous .check() completed: nothing to do
  445. return
  446. if self._checked:
  447. # Recursed: C struct contains itself
  448. raise QAPISemError(self.info,
  449. "object %s contains itself" % self.name)
  450. super().check(schema)
  451. assert self._checked and not self._check_complete
  452. seen = OrderedDict()
  453. if self._base_name:
  454. self.base = schema.resolve_type(self._base_name, self.info,
  455. "'base'")
  456. if (not isinstance(self.base, QAPISchemaObjectType)
  457. or self.base.variants):
  458. raise QAPISemError(
  459. self.info,
  460. "'base' requires a struct type, %s isn't"
  461. % self.base.describe())
  462. self.base.check(schema)
  463. self.base.check_clash(self.info, seen)
  464. for m in self.local_members:
  465. m.check(schema)
  466. m.check_clash(self.info, seen)
  467. # self.check_clash() works in terms of the supertype, but
  468. # self.members is declared List[QAPISchemaObjectTypeMember].
  469. # Cast down to the subtype.
  470. members = cast(List[QAPISchemaObjectTypeMember], list(seen.values()))
  471. if self.variants:
  472. self.variants.check(schema, seen)
  473. self.variants.check_clash(self.info, seen)
  474. self.members = members
  475. self._check_complete = True # mark completed
  476. # Check that the members of this type do not cause duplicate JSON members,
  477. # and update seen to track the members seen so far. Report any errors
  478. # on behalf of info, which is not necessarily self.info
  479. def check_clash(
  480. self,
  481. info: Optional[QAPISourceInfo],
  482. seen: Dict[str, QAPISchemaMember],
  483. ) -> None:
  484. assert self._checked
  485. for m in self.members:
  486. m.check_clash(info, seen)
  487. if self.variants:
  488. self.variants.check_clash(info, seen)
  489. def connect_doc(self, doc: Optional[QAPIDoc] = None) -> None:
  490. super().connect_doc(doc)
  491. doc = doc or self.doc
  492. if self.base and self.base.is_implicit():
  493. self.base.connect_doc(doc)
  494. for m in self.local_members:
  495. m.connect_doc(doc)
  496. def is_implicit(self) -> bool:
  497. # See QAPISchema._make_implicit_object_type(), as well as
  498. # _def_predefineds()
  499. return self.name.startswith('q_')
  500. def is_empty(self) -> bool:
  501. return not self.members and not self.variants
  502. def has_conditional_members(self) -> bool:
  503. return any(m.ifcond.is_present() for m in self.members)
  504. def c_name(self) -> str:
  505. assert self.name != 'q_empty'
  506. return super().c_name()
  507. def c_type(self) -> str:
  508. assert not self.is_implicit()
  509. return c_name(self.name) + POINTER_SUFFIX
  510. def c_unboxed_type(self) -> str:
  511. return c_name(self.name)
  512. def json_type(self) -> str:
  513. return 'object'
  514. def visit(self, visitor: QAPISchemaVisitor) -> None:
  515. super().visit(visitor)
  516. visitor.visit_object_type(
  517. self.name, self.info, self.ifcond, self.features,
  518. self.base, self.local_members, self.variants)
  519. visitor.visit_object_type_flat(
  520. self.name, self.info, self.ifcond, self.features,
  521. self.members, self.variants)
  522. class QAPISchemaAlternateType(QAPISchemaType):
  523. meta = 'alternate'
  524. def __init__(
  525. self,
  526. name: str,
  527. info: QAPISourceInfo,
  528. doc: Optional[QAPIDoc],
  529. ifcond: Optional[QAPISchemaIfCond],
  530. features: List[QAPISchemaFeature],
  531. variants: QAPISchemaVariants,
  532. ):
  533. super().__init__(name, info, doc, ifcond, features)
  534. assert variants.tag_member
  535. variants.set_defined_in(name)
  536. variants.tag_member.set_defined_in(self.name)
  537. self.variants = variants
  538. def check(self, schema: QAPISchema) -> None:
  539. super().check(schema)
  540. self.variants.tag_member.check(schema)
  541. # Not calling self.variants.check_clash(), because there's nothing
  542. # to clash with
  543. self.variants.check(schema, {})
  544. # Alternate branch names have no relation to the tag enum values;
  545. # so we have to check for potential name collisions ourselves.
  546. seen: Dict[str, QAPISchemaMember] = {}
  547. types_seen: Dict[str, str] = {}
  548. for v in self.variants.variants:
  549. v.check_clash(self.info, seen)
  550. qtype = v.type.alternate_qtype()
  551. if not qtype:
  552. raise QAPISemError(
  553. self.info,
  554. "%s cannot use %s"
  555. % (v.describe(self.info), v.type.describe()))
  556. conflicting = set([qtype])
  557. if qtype == 'QTYPE_QSTRING':
  558. if isinstance(v.type, QAPISchemaEnumType):
  559. for m in v.type.members:
  560. if m.name in ['on', 'off']:
  561. conflicting.add('QTYPE_QBOOL')
  562. if re.match(r'[-+0-9.]', m.name):
  563. # lazy, could be tightened
  564. conflicting.add('QTYPE_QNUM')
  565. else:
  566. conflicting.add('QTYPE_QNUM')
  567. conflicting.add('QTYPE_QBOOL')
  568. for qt in conflicting:
  569. if qt in types_seen:
  570. raise QAPISemError(
  571. self.info,
  572. "%s can't be distinguished from '%s'"
  573. % (v.describe(self.info), types_seen[qt]))
  574. types_seen[qt] = v.name
  575. def connect_doc(self, doc: Optional[QAPIDoc] = None) -> None:
  576. super().connect_doc(doc)
  577. doc = doc or self.doc
  578. for v in self.variants.variants:
  579. v.connect_doc(doc)
  580. def c_type(self) -> str:
  581. return c_name(self.name) + POINTER_SUFFIX
  582. def json_type(self) -> str:
  583. return 'value'
  584. def visit(self, visitor: QAPISchemaVisitor) -> None:
  585. super().visit(visitor)
  586. visitor.visit_alternate_type(
  587. self.name, self.info, self.ifcond, self.features, self.variants)
  588. class QAPISchemaVariants:
  589. def __init__(
  590. self,
  591. tag_name: Optional[str],
  592. info: QAPISourceInfo,
  593. tag_member: Optional[QAPISchemaObjectTypeMember],
  594. variants: List[QAPISchemaVariant],
  595. ):
  596. # Unions pass tag_name but not tag_member.
  597. # Alternates pass tag_member but not tag_name.
  598. # After check(), tag_member is always set.
  599. assert bool(tag_member) != bool(tag_name)
  600. assert (isinstance(tag_name, str) or
  601. isinstance(tag_member, QAPISchemaObjectTypeMember))
  602. self._tag_name = tag_name
  603. self.info = info
  604. self._tag_member = tag_member
  605. self.variants = variants
  606. @property
  607. def tag_member(self) -> QAPISchemaObjectTypeMember:
  608. if self._tag_member is None:
  609. raise RuntimeError(
  610. "QAPISchemaVariants has no tag_member property until "
  611. "after check() has been run."
  612. )
  613. return self._tag_member
  614. def set_defined_in(self, name: str) -> None:
  615. for v in self.variants:
  616. v.set_defined_in(name)
  617. def check(
  618. self, schema: QAPISchema, seen: Dict[str, QAPISchemaMember]
  619. ) -> None:
  620. if self._tag_name: # union
  621. # We need to narrow the member type:
  622. tmp = seen.get(c_name(self._tag_name))
  623. assert tmp is None or isinstance(tmp, QAPISchemaObjectTypeMember)
  624. self._tag_member = tmp
  625. base = "'base'"
  626. # Pointing to the base type when not implicit would be
  627. # nice, but we don't know it here
  628. if not self._tag_member or self._tag_name != self._tag_member.name:
  629. raise QAPISemError(
  630. self.info,
  631. "discriminator '%s' is not a member of %s"
  632. % (self._tag_name, base))
  633. # Here we do:
  634. assert self.tag_member.defined_in
  635. base_type = schema.lookup_type(self.tag_member.defined_in)
  636. assert base_type
  637. if not base_type.is_implicit():
  638. base = "base type '%s'" % self.tag_member.defined_in
  639. if not isinstance(self.tag_member.type, QAPISchemaEnumType):
  640. raise QAPISemError(
  641. self.info,
  642. "discriminator member '%s' of %s must be of enum type"
  643. % (self._tag_name, base))
  644. if self.tag_member.optional:
  645. raise QAPISemError(
  646. self.info,
  647. "discriminator member '%s' of %s must not be optional"
  648. % (self._tag_name, base))
  649. if self.tag_member.ifcond.is_present():
  650. raise QAPISemError(
  651. self.info,
  652. "discriminator member '%s' of %s must not be conditional"
  653. % (self._tag_name, base))
  654. else: # alternate
  655. assert self._tag_member
  656. assert isinstance(self.tag_member.type, QAPISchemaEnumType)
  657. assert not self.tag_member.optional
  658. assert not self.tag_member.ifcond.is_present()
  659. if self._tag_name: # union
  660. # branches that are not explicitly covered get an empty type
  661. assert self.tag_member.defined_in
  662. cases = {v.name for v in self.variants}
  663. for m in self.tag_member.type.members:
  664. if m.name not in cases:
  665. v = QAPISchemaVariant(m.name, self.info,
  666. 'q_empty', m.ifcond)
  667. v.set_defined_in(self.tag_member.defined_in)
  668. self.variants.append(v)
  669. if not self.variants:
  670. raise QAPISemError(self.info, "union has no branches")
  671. for v in self.variants:
  672. v.check(schema)
  673. # Union names must match enum values; alternate names are
  674. # checked separately. Use 'seen' to tell the two apart.
  675. if seen:
  676. if v.name not in self.tag_member.type.member_names():
  677. raise QAPISemError(
  678. self.info,
  679. "branch '%s' is not a value of %s"
  680. % (v.name, self.tag_member.type.describe()))
  681. if not isinstance(v.type, QAPISchemaObjectType):
  682. raise QAPISemError(
  683. self.info,
  684. "%s cannot use %s"
  685. % (v.describe(self.info), v.type.describe()))
  686. v.type.check(schema)
  687. def check_clash(
  688. self,
  689. info: Optional[QAPISourceInfo],
  690. seen: Dict[str, QAPISchemaMember],
  691. ) -> None:
  692. for v in self.variants:
  693. # Reset seen map for each variant, since qapi names from one
  694. # branch do not affect another branch.
  695. #
  696. # v.type's typing is enforced in check() above.
  697. assert isinstance(v.type, QAPISchemaObjectType)
  698. v.type.check_clash(info, dict(seen))
  699. class QAPISchemaMember:
  700. """ Represents object members, enum members and features """
  701. role = 'member'
  702. def __init__(
  703. self,
  704. name: str,
  705. info: Optional[QAPISourceInfo],
  706. ifcond: Optional[QAPISchemaIfCond] = None,
  707. ):
  708. self.name = name
  709. self.info = info
  710. self.ifcond = ifcond or QAPISchemaIfCond()
  711. self.defined_in: Optional[str] = None
  712. def set_defined_in(self, name: str) -> None:
  713. assert not self.defined_in
  714. self.defined_in = name
  715. def check_clash(
  716. self,
  717. info: Optional[QAPISourceInfo],
  718. seen: Dict[str, QAPISchemaMember],
  719. ) -> None:
  720. cname = c_name(self.name)
  721. if cname in seen:
  722. raise QAPISemError(
  723. info,
  724. "%s collides with %s"
  725. % (self.describe(info), seen[cname].describe(info)))
  726. seen[cname] = self
  727. def connect_doc(self, doc: Optional[QAPIDoc]) -> None:
  728. if doc:
  729. doc.connect_member(self)
  730. def describe(self, info: Optional[QAPISourceInfo]) -> str:
  731. role = self.role
  732. meta = 'type'
  733. defined_in = self.defined_in
  734. assert defined_in
  735. if defined_in.startswith('q_obj_'):
  736. # See QAPISchema._make_implicit_object_type() - reverse the
  737. # mapping there to create a nice human-readable description
  738. defined_in = defined_in[6:]
  739. if defined_in.endswith('-arg'):
  740. # Implicit type created for a command's dict 'data'
  741. assert role == 'member'
  742. role = 'parameter'
  743. meta = 'command'
  744. defined_in = defined_in[:-4]
  745. elif defined_in.endswith('-base'):
  746. # Implicit type created for a union's dict 'base'
  747. role = 'base ' + role
  748. defined_in = defined_in[:-5]
  749. else:
  750. assert False
  751. assert info is not None
  752. if defined_in != info.defn_name:
  753. return "%s '%s' of %s '%s'" % (role, self.name, meta, defined_in)
  754. return "%s '%s'" % (role, self.name)
  755. class QAPISchemaEnumMember(QAPISchemaMember):
  756. role = 'value'
  757. def __init__(
  758. self,
  759. name: str,
  760. info: Optional[QAPISourceInfo],
  761. ifcond: Optional[QAPISchemaIfCond] = None,
  762. features: Optional[List[QAPISchemaFeature]] = None,
  763. ):
  764. super().__init__(name, info, ifcond)
  765. for f in features or []:
  766. f.set_defined_in(name)
  767. self.features = features or []
  768. def connect_doc(self, doc: Optional[QAPIDoc]) -> None:
  769. super().connect_doc(doc)
  770. if doc:
  771. for f in self.features:
  772. doc.connect_feature(f)
  773. class QAPISchemaFeature(QAPISchemaMember):
  774. role = 'feature'
  775. def is_special(self) -> bool:
  776. return self.name in ('deprecated', 'unstable')
  777. class QAPISchemaObjectTypeMember(QAPISchemaMember):
  778. def __init__(
  779. self,
  780. name: str,
  781. info: QAPISourceInfo,
  782. typ: str,
  783. optional: bool,
  784. ifcond: Optional[QAPISchemaIfCond] = None,
  785. features: Optional[List[QAPISchemaFeature]] = None,
  786. ):
  787. super().__init__(name, info, ifcond)
  788. for f in features or []:
  789. f.set_defined_in(name)
  790. self._type_name = typ
  791. self.type: QAPISchemaType # set during check()
  792. self.optional = optional
  793. self.features = features or []
  794. def need_has(self) -> bool:
  795. return self.optional and self.type.need_has_if_optional()
  796. def check(self, schema: QAPISchema) -> None:
  797. assert self.defined_in
  798. self.type = schema.resolve_type(self._type_name, self.info,
  799. self.describe)
  800. seen: Dict[str, QAPISchemaMember] = {}
  801. for f in self.features:
  802. f.check_clash(self.info, seen)
  803. def connect_doc(self, doc: Optional[QAPIDoc]) -> None:
  804. super().connect_doc(doc)
  805. if doc:
  806. for f in self.features:
  807. doc.connect_feature(f)
  808. class QAPISchemaVariant(QAPISchemaObjectTypeMember):
  809. role = 'branch'
  810. def __init__(
  811. self,
  812. name: str,
  813. info: QAPISourceInfo,
  814. typ: str,
  815. ifcond: QAPISchemaIfCond,
  816. ):
  817. super().__init__(name, info, typ, False, ifcond)
  818. class QAPISchemaCommand(QAPISchemaDefinition):
  819. meta = 'command'
  820. def __init__(
  821. self,
  822. name: str,
  823. info: QAPISourceInfo,
  824. doc: Optional[QAPIDoc],
  825. ifcond: QAPISchemaIfCond,
  826. features: List[QAPISchemaFeature],
  827. arg_type: Optional[str],
  828. ret_type: Optional[str],
  829. gen: bool,
  830. success_response: bool,
  831. boxed: bool,
  832. allow_oob: bool,
  833. allow_preconfig: bool,
  834. coroutine: bool,
  835. ):
  836. super().__init__(name, info, doc, ifcond, features)
  837. self._arg_type_name = arg_type
  838. self.arg_type: Optional[QAPISchemaObjectType] = None
  839. self._ret_type_name = ret_type
  840. self.ret_type: Optional[QAPISchemaType] = None
  841. self.gen = gen
  842. self.success_response = success_response
  843. self.boxed = boxed
  844. self.allow_oob = allow_oob
  845. self.allow_preconfig = allow_preconfig
  846. self.coroutine = coroutine
  847. def check(self, schema: QAPISchema) -> None:
  848. assert self.info is not None
  849. super().check(schema)
  850. if self._arg_type_name:
  851. arg_type = schema.resolve_type(
  852. self._arg_type_name, self.info, "command's 'data'")
  853. if not isinstance(arg_type, QAPISchemaObjectType):
  854. raise QAPISemError(
  855. self.info,
  856. "command's 'data' cannot take %s"
  857. % arg_type.describe())
  858. self.arg_type = arg_type
  859. if self.arg_type.variants and not self.boxed:
  860. raise QAPISemError(
  861. self.info,
  862. "command's 'data' can take %s only with 'boxed': true"
  863. % self.arg_type.describe())
  864. self.arg_type.check(schema)
  865. if self.arg_type.has_conditional_members() and not self.boxed:
  866. raise QAPISemError(
  867. self.info,
  868. "conditional command arguments require 'boxed': true")
  869. if self._ret_type_name:
  870. self.ret_type = schema.resolve_type(
  871. self._ret_type_name, self.info, "command's 'returns'")
  872. if self.name not in self.info.pragma.command_returns_exceptions:
  873. typ = self.ret_type
  874. if isinstance(typ, QAPISchemaArrayType):
  875. typ = typ.element_type
  876. if not isinstance(typ, QAPISchemaObjectType):
  877. raise QAPISemError(
  878. self.info,
  879. "command's 'returns' cannot take %s"
  880. % self.ret_type.describe())
  881. def connect_doc(self, doc: Optional[QAPIDoc] = None) -> None:
  882. super().connect_doc(doc)
  883. doc = doc or self.doc
  884. if doc:
  885. if self.arg_type and self.arg_type.is_implicit():
  886. self.arg_type.connect_doc(doc)
  887. def visit(self, visitor: QAPISchemaVisitor) -> None:
  888. super().visit(visitor)
  889. visitor.visit_command(
  890. self.name, self.info, self.ifcond, self.features,
  891. self.arg_type, self.ret_type, self.gen, self.success_response,
  892. self.boxed, self.allow_oob, self.allow_preconfig,
  893. self.coroutine)
  894. class QAPISchemaEvent(QAPISchemaDefinition):
  895. meta = 'event'
  896. def __init__(
  897. self,
  898. name: str,
  899. info: QAPISourceInfo,
  900. doc: Optional[QAPIDoc],
  901. ifcond: QAPISchemaIfCond,
  902. features: List[QAPISchemaFeature],
  903. arg_type: Optional[str],
  904. boxed: bool,
  905. ):
  906. super().__init__(name, info, doc, ifcond, features)
  907. self._arg_type_name = arg_type
  908. self.arg_type: Optional[QAPISchemaObjectType] = None
  909. self.boxed = boxed
  910. def check(self, schema: QAPISchema) -> None:
  911. super().check(schema)
  912. if self._arg_type_name:
  913. typ = schema.resolve_type(
  914. self._arg_type_name, self.info, "event's 'data'")
  915. if not isinstance(typ, QAPISchemaObjectType):
  916. raise QAPISemError(
  917. self.info,
  918. "event's 'data' cannot take %s"
  919. % typ.describe())
  920. self.arg_type = typ
  921. if self.arg_type.variants and not self.boxed:
  922. raise QAPISemError(
  923. self.info,
  924. "event's 'data' can take %s only with 'boxed': true"
  925. % self.arg_type.describe())
  926. self.arg_type.check(schema)
  927. if self.arg_type.has_conditional_members() and not self.boxed:
  928. raise QAPISemError(
  929. self.info,
  930. "conditional event arguments require 'boxed': true")
  931. def connect_doc(self, doc: Optional[QAPIDoc] = None) -> None:
  932. super().connect_doc(doc)
  933. doc = doc or self.doc
  934. if doc:
  935. if self.arg_type and self.arg_type.is_implicit():
  936. self.arg_type.connect_doc(doc)
  937. def visit(self, visitor: QAPISchemaVisitor) -> None:
  938. super().visit(visitor)
  939. visitor.visit_event(
  940. self.name, self.info, self.ifcond, self.features,
  941. self.arg_type, self.boxed)
  942. class QAPISchema:
  943. def __init__(self, fname: str):
  944. self.fname = fname
  945. try:
  946. parser = QAPISchemaParser(fname)
  947. except OSError as err:
  948. raise QAPIError(
  949. f"can't read schema file '{fname}': {err.strerror}"
  950. ) from err
  951. exprs = check_exprs(parser.exprs)
  952. self.docs = parser.docs
  953. self._entity_list: List[QAPISchemaEntity] = []
  954. self._entity_dict: Dict[str, QAPISchemaDefinition] = {}
  955. self._module_dict: Dict[str, QAPISchemaModule] = OrderedDict()
  956. self._schema_dir = os.path.dirname(fname)
  957. self._make_module(QAPISchemaModule.BUILTIN_MODULE_NAME)
  958. self._make_module(fname)
  959. self._predefining = True
  960. self._def_predefineds()
  961. self._predefining = False
  962. self._def_exprs(exprs)
  963. self.check()
  964. def _def_entity(self, ent: QAPISchemaEntity) -> None:
  965. self._entity_list.append(ent)
  966. def _def_definition(self, defn: QAPISchemaDefinition) -> None:
  967. # Only the predefined types are allowed to not have info
  968. assert defn.info or self._predefining
  969. self._def_entity(defn)
  970. # TODO reject names that differ only in '_' vs. '.' vs. '-',
  971. # because they're liable to clash in generated C.
  972. other_defn = self._entity_dict.get(defn.name)
  973. if other_defn:
  974. if other_defn.info:
  975. where = QAPISourceError(other_defn.info, "previous definition")
  976. raise QAPISemError(
  977. defn.info,
  978. "'%s' is already defined\n%s" % (defn.name, where))
  979. raise QAPISemError(
  980. defn.info, "%s is already defined" % other_defn.describe())
  981. self._entity_dict[defn.name] = defn
  982. def lookup_entity(self,name: str) -> Optional[QAPISchemaEntity]:
  983. return self._entity_dict.get(name)
  984. def lookup_type(self, name: str) -> Optional[QAPISchemaType]:
  985. typ = self.lookup_entity(name)
  986. if isinstance(typ, QAPISchemaType):
  987. return typ
  988. return None
  989. def resolve_type(
  990. self,
  991. name: str,
  992. info: Optional[QAPISourceInfo],
  993. what: Union[None, str, Callable[[QAPISourceInfo], str]],
  994. ) -> QAPISchemaType:
  995. typ = self.lookup_type(name)
  996. if not typ:
  997. assert info and what # built-in types must not fail lookup
  998. if callable(what):
  999. what = what(info)
  1000. raise QAPISemError(
  1001. info, "%s uses unknown type '%s'" % (what, name))
  1002. return typ
  1003. def _module_name(self, fname: str) -> str:
  1004. if QAPISchemaModule.is_system_module(fname):
  1005. return fname
  1006. return os.path.relpath(fname, self._schema_dir)
  1007. def _make_module(self, fname: str) -> QAPISchemaModule:
  1008. name = self._module_name(fname)
  1009. if name not in self._module_dict:
  1010. self._module_dict[name] = QAPISchemaModule(name)
  1011. return self._module_dict[name]
  1012. def module_by_fname(self, fname: str) -> QAPISchemaModule:
  1013. name = self._module_name(fname)
  1014. return self._module_dict[name]
  1015. def _def_include(self, expr: QAPIExpression) -> None:
  1016. include = expr['include']
  1017. assert expr.doc is None
  1018. self._def_entity(
  1019. QAPISchemaInclude(self._make_module(include), expr.info))
  1020. def _def_builtin_type(
  1021. self, name: str, json_type: str, c_type: str
  1022. ) -> None:
  1023. self._def_definition(QAPISchemaBuiltinType(name, json_type, c_type))
  1024. # Instantiating only the arrays that are actually used would
  1025. # be nice, but we can't as long as their generated code
  1026. # (qapi-builtin-types.[ch]) may be shared by some other
  1027. # schema.
  1028. self._make_array_type(name, None)
  1029. def _def_predefineds(self) -> None:
  1030. for t in [('str', 'string', 'char' + POINTER_SUFFIX),
  1031. ('number', 'number', 'double'),
  1032. ('int', 'int', 'int64_t'),
  1033. ('int8', 'int', 'int8_t'),
  1034. ('int16', 'int', 'int16_t'),
  1035. ('int32', 'int', 'int32_t'),
  1036. ('int64', 'int', 'int64_t'),
  1037. ('uint8', 'int', 'uint8_t'),
  1038. ('uint16', 'int', 'uint16_t'),
  1039. ('uint32', 'int', 'uint32_t'),
  1040. ('uint64', 'int', 'uint64_t'),
  1041. ('size', 'int', 'uint64_t'),
  1042. ('bool', 'boolean', 'bool'),
  1043. ('any', 'value', 'QObject' + POINTER_SUFFIX),
  1044. ('null', 'null', 'QNull' + POINTER_SUFFIX)]:
  1045. self._def_builtin_type(*t)
  1046. self.the_empty_object_type = QAPISchemaObjectType(
  1047. 'q_empty', None, None, None, None, None, [], None)
  1048. self._def_definition(self.the_empty_object_type)
  1049. qtypes = ['none', 'qnull', 'qnum', 'qstring', 'qdict', 'qlist',
  1050. 'qbool']
  1051. qtype_values = self._make_enum_members(
  1052. [{'name': n} for n in qtypes], None)
  1053. self._def_definition(QAPISchemaEnumType(
  1054. 'QType', None, None, None, None, qtype_values, 'QTYPE'))
  1055. def _make_features(
  1056. self,
  1057. features: Optional[List[Dict[str, Any]]],
  1058. info: Optional[QAPISourceInfo],
  1059. ) -> List[QAPISchemaFeature]:
  1060. if features is None:
  1061. return []
  1062. return [QAPISchemaFeature(f['name'], info,
  1063. QAPISchemaIfCond(f.get('if')))
  1064. for f in features]
  1065. def _make_enum_member(
  1066. self,
  1067. name: str,
  1068. ifcond: Optional[Union[str, Dict[str, Any]]],
  1069. features: Optional[List[Dict[str, Any]]],
  1070. info: Optional[QAPISourceInfo],
  1071. ) -> QAPISchemaEnumMember:
  1072. return QAPISchemaEnumMember(name, info,
  1073. QAPISchemaIfCond(ifcond),
  1074. self._make_features(features, info))
  1075. def _make_enum_members(
  1076. self, values: List[Dict[str, Any]], info: Optional[QAPISourceInfo]
  1077. ) -> List[QAPISchemaEnumMember]:
  1078. return [self._make_enum_member(v['name'], v.get('if'),
  1079. v.get('features'), info)
  1080. for v in values]
  1081. def _make_array_type(
  1082. self, element_type: str, info: Optional[QAPISourceInfo]
  1083. ) -> str:
  1084. name = element_type + 'List' # reserved by check_defn_name_str()
  1085. if not self.lookup_type(name):
  1086. self._def_definition(QAPISchemaArrayType(
  1087. name, info, element_type))
  1088. return name
  1089. def _make_implicit_object_type(
  1090. self,
  1091. name: str,
  1092. info: QAPISourceInfo,
  1093. ifcond: QAPISchemaIfCond,
  1094. role: str,
  1095. members: List[QAPISchemaObjectTypeMember],
  1096. ) -> Optional[str]:
  1097. if not members:
  1098. return None
  1099. # See also QAPISchemaObjectTypeMember.describe()
  1100. name = 'q_obj_%s-%s' % (name, role)
  1101. typ = self.lookup_entity(name)
  1102. if typ:
  1103. assert(isinstance(typ, QAPISchemaObjectType))
  1104. # The implicit object type has multiple users. This can
  1105. # only be a duplicate definition, which will be flagged
  1106. # later.
  1107. pass
  1108. else:
  1109. self._def_definition(QAPISchemaObjectType(
  1110. name, info, None, ifcond, None, None, members, None))
  1111. return name
  1112. def _def_enum_type(self, expr: QAPIExpression) -> None:
  1113. name = expr['enum']
  1114. data = expr['data']
  1115. prefix = expr.get('prefix')
  1116. ifcond = QAPISchemaIfCond(expr.get('if'))
  1117. info = expr.info
  1118. features = self._make_features(expr.get('features'), info)
  1119. self._def_definition(QAPISchemaEnumType(
  1120. name, info, expr.doc, ifcond, features,
  1121. self._make_enum_members(data, info), prefix))
  1122. def _make_member(
  1123. self,
  1124. name: str,
  1125. typ: Union[List[str], str],
  1126. ifcond: QAPISchemaIfCond,
  1127. features: Optional[List[Dict[str, Any]]],
  1128. info: QAPISourceInfo,
  1129. ) -> QAPISchemaObjectTypeMember:
  1130. optional = False
  1131. if name.startswith('*'):
  1132. name = name[1:]
  1133. optional = True
  1134. if isinstance(typ, list):
  1135. assert len(typ) == 1
  1136. typ = self._make_array_type(typ[0], info)
  1137. return QAPISchemaObjectTypeMember(name, info, typ, optional, ifcond,
  1138. self._make_features(features, info))
  1139. def _make_members(
  1140. self,
  1141. data: Dict[str, Any],
  1142. info: QAPISourceInfo,
  1143. ) -> List[QAPISchemaObjectTypeMember]:
  1144. return [self._make_member(key, value['type'],
  1145. QAPISchemaIfCond(value.get('if')),
  1146. value.get('features'), info)
  1147. for (key, value) in data.items()]
  1148. def _def_struct_type(self, expr: QAPIExpression) -> None:
  1149. name = expr['struct']
  1150. base = expr.get('base')
  1151. data = expr['data']
  1152. info = expr.info
  1153. ifcond = QAPISchemaIfCond(expr.get('if'))
  1154. features = self._make_features(expr.get('features'), info)
  1155. self._def_definition(QAPISchemaObjectType(
  1156. name, info, expr.doc, ifcond, features, base,
  1157. self._make_members(data, info),
  1158. None))
  1159. def _make_variant(
  1160. self,
  1161. case: str,
  1162. typ: str,
  1163. ifcond: QAPISchemaIfCond,
  1164. info: QAPISourceInfo,
  1165. ) -> QAPISchemaVariant:
  1166. if isinstance(typ, list):
  1167. assert len(typ) == 1
  1168. typ = self._make_array_type(typ[0], info)
  1169. return QAPISchemaVariant(case, info, typ, ifcond)
  1170. def _def_union_type(self, expr: QAPIExpression) -> None:
  1171. name = expr['union']
  1172. base = expr['base']
  1173. tag_name = expr['discriminator']
  1174. data = expr['data']
  1175. assert isinstance(data, dict)
  1176. info = expr.info
  1177. ifcond = QAPISchemaIfCond(expr.get('if'))
  1178. features = self._make_features(expr.get('features'), info)
  1179. if isinstance(base, dict):
  1180. base = self._make_implicit_object_type(
  1181. name, info, ifcond,
  1182. 'base', self._make_members(base, info))
  1183. variants = [
  1184. self._make_variant(key, value['type'],
  1185. QAPISchemaIfCond(value.get('if')),
  1186. info)
  1187. for (key, value) in data.items()]
  1188. members: List[QAPISchemaObjectTypeMember] = []
  1189. self._def_definition(
  1190. QAPISchemaObjectType(name, info, expr.doc, ifcond, features,
  1191. base, members,
  1192. QAPISchemaVariants(
  1193. tag_name, info, None, variants)))
  1194. def _def_alternate_type(self, expr: QAPIExpression) -> None:
  1195. name = expr['alternate']
  1196. data = expr['data']
  1197. assert isinstance(data, dict)
  1198. ifcond = QAPISchemaIfCond(expr.get('if'))
  1199. info = expr.info
  1200. features = self._make_features(expr.get('features'), info)
  1201. variants = [
  1202. self._make_variant(key, value['type'],
  1203. QAPISchemaIfCond(value.get('if')),
  1204. info)
  1205. for (key, value) in data.items()]
  1206. tag_member = QAPISchemaObjectTypeMember('type', info, 'QType', False)
  1207. self._def_definition(
  1208. QAPISchemaAlternateType(
  1209. name, info, expr.doc, ifcond, features,
  1210. QAPISchemaVariants(None, info, tag_member, variants)))
  1211. def _def_command(self, expr: QAPIExpression) -> None:
  1212. name = expr['command']
  1213. data = expr.get('data')
  1214. rets = expr.get('returns')
  1215. gen = expr.get('gen', True)
  1216. success_response = expr.get('success-response', True)
  1217. boxed = expr.get('boxed', False)
  1218. allow_oob = expr.get('allow-oob', False)
  1219. allow_preconfig = expr.get('allow-preconfig', False)
  1220. coroutine = expr.get('coroutine', False)
  1221. ifcond = QAPISchemaIfCond(expr.get('if'))
  1222. info = expr.info
  1223. features = self._make_features(expr.get('features'), info)
  1224. if isinstance(data, OrderedDict):
  1225. data = self._make_implicit_object_type(
  1226. name, info, ifcond,
  1227. 'arg', self._make_members(data, info))
  1228. if isinstance(rets, list):
  1229. assert len(rets) == 1
  1230. rets = self._make_array_type(rets[0], info)
  1231. self._def_definition(
  1232. QAPISchemaCommand(name, info, expr.doc, ifcond, features, data,
  1233. rets, gen, success_response, boxed, allow_oob,
  1234. allow_preconfig, coroutine))
  1235. def _def_event(self, expr: QAPIExpression) -> None:
  1236. name = expr['event']
  1237. data = expr.get('data')
  1238. boxed = expr.get('boxed', False)
  1239. ifcond = QAPISchemaIfCond(expr.get('if'))
  1240. info = expr.info
  1241. features = self._make_features(expr.get('features'), info)
  1242. if isinstance(data, OrderedDict):
  1243. data = self._make_implicit_object_type(
  1244. name, info, ifcond,
  1245. 'arg', self._make_members(data, info))
  1246. self._def_definition(QAPISchemaEvent(name, info, expr.doc, ifcond,
  1247. features, data, boxed))
  1248. def _def_exprs(self, exprs: List[QAPIExpression]) -> None:
  1249. for expr in exprs:
  1250. if 'enum' in expr:
  1251. self._def_enum_type(expr)
  1252. elif 'struct' in expr:
  1253. self._def_struct_type(expr)
  1254. elif 'union' in expr:
  1255. self._def_union_type(expr)
  1256. elif 'alternate' in expr:
  1257. self._def_alternate_type(expr)
  1258. elif 'command' in expr:
  1259. self._def_command(expr)
  1260. elif 'event' in expr:
  1261. self._def_event(expr)
  1262. elif 'include' in expr:
  1263. self._def_include(expr)
  1264. else:
  1265. assert False
  1266. def check(self) -> None:
  1267. for ent in self._entity_list:
  1268. ent.check(self)
  1269. ent.connect_doc()
  1270. for ent in self._entity_list:
  1271. ent.set_module(self)
  1272. for doc in self.docs:
  1273. doc.check()
  1274. def visit(self, visitor: QAPISchemaVisitor) -> None:
  1275. visitor.visit_begin(self)
  1276. for mod in self._module_dict.values():
  1277. mod.visit(visitor)
  1278. visitor.visit_end()