schema.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492
  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. branches: Optional[QAPISchemaBranches],
  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. branches: Optional[QAPISchemaBranches],
  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. alternatives: QAPISchemaAlternatives,
  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. branches: Optional[QAPISchemaBranches],
  424. ):
  425. # struct has local_members, optional base, and no branches
  426. # union has base, branches, and no local_members
  427. super().__init__(name, info, doc, ifcond, features)
  428. self.meta = 'union' if branches else 'struct'
  429. for m in local_members:
  430. m.set_defined_in(name)
  431. if branches is not None:
  432. branches.set_defined_in(name)
  433. self._base_name = base
  434. self.base = None
  435. self.local_members = local_members
  436. self.branches = branches
  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.branches):
  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.branches:
  472. self.branches.check(schema, seen)
  473. self.branches.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.branches:
  488. self.branches.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.branches
  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.branches)
  519. visitor.visit_object_type_flat(
  520. self.name, self.info, self.ifcond, self.features,
  521. self.members, self.branches)
  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. alternatives: QAPISchemaAlternatives,
  532. ):
  533. super().__init__(name, info, doc, ifcond, features)
  534. assert alternatives.tag_member
  535. alternatives.set_defined_in(name)
  536. alternatives.tag_member.set_defined_in(self.name)
  537. self.alternatives = alternatives
  538. def check(self, schema: QAPISchema) -> None:
  539. super().check(schema)
  540. self.alternatives.tag_member.check(schema)
  541. # Not calling self.alternatives.check_clash(), because there's
  542. # nothing to clash with
  543. self.alternatives.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.alternatives.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.alternatives.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,
  588. self.alternatives)
  589. class QAPISchemaVariants:
  590. def __init__(
  591. self,
  592. info: QAPISourceInfo,
  593. variants: List[QAPISchemaVariant],
  594. ):
  595. self.info = info
  596. self.tag_member: QAPISchemaObjectTypeMember
  597. self.variants = variants
  598. def set_defined_in(self, name: str) -> None:
  599. for v in self.variants:
  600. v.set_defined_in(name)
  601. # pylint: disable=unused-argument
  602. def check(
  603. self, schema: QAPISchema, seen: Dict[str, QAPISchemaMember]
  604. ) -> None:
  605. for v in self.variants:
  606. v.check(schema)
  607. class QAPISchemaBranches(QAPISchemaVariants):
  608. def __init__(self,
  609. info: QAPISourceInfo,
  610. variants: List[QAPISchemaVariant],
  611. tag_name: str):
  612. super().__init__(info, variants)
  613. self._tag_name = tag_name
  614. def check(
  615. self, schema: QAPISchema, seen: Dict[str, QAPISchemaMember]
  616. ) -> None:
  617. # We need to narrow the member type:
  618. tag_member = seen.get(c_name(self._tag_name))
  619. assert (tag_member is None
  620. or isinstance(tag_member, QAPISchemaObjectTypeMember))
  621. base = "'base'"
  622. # Pointing to the base type when not implicit would be
  623. # nice, but we don't know it here
  624. if not tag_member or self._tag_name != tag_member.name:
  625. raise QAPISemError(
  626. self.info,
  627. "discriminator '%s' is not a member of %s"
  628. % (self._tag_name, base))
  629. self.tag_member = tag_member
  630. # Here we do:
  631. assert tag_member.defined_in
  632. base_type = schema.lookup_type(tag_member.defined_in)
  633. assert base_type
  634. if not base_type.is_implicit():
  635. base = "base type '%s'" % tag_member.defined_in
  636. if not isinstance(tag_member.type, QAPISchemaEnumType):
  637. raise QAPISemError(
  638. self.info,
  639. "discriminator member '%s' of %s must be of enum type"
  640. % (self._tag_name, base))
  641. if tag_member.optional:
  642. raise QAPISemError(
  643. self.info,
  644. "discriminator member '%s' of %s must not be optional"
  645. % (self._tag_name, base))
  646. if tag_member.ifcond.is_present():
  647. raise QAPISemError(
  648. self.info,
  649. "discriminator member '%s' of %s must not be conditional"
  650. % (self._tag_name, base))
  651. # branches that are not explicitly covered get an empty type
  652. assert tag_member.defined_in
  653. cases = {v.name for v in self.variants}
  654. for m in tag_member.type.members:
  655. if m.name not in cases:
  656. v = QAPISchemaVariant(m.name, self.info,
  657. 'q_empty', m.ifcond)
  658. v.set_defined_in(tag_member.defined_in)
  659. self.variants.append(v)
  660. if not self.variants:
  661. raise QAPISemError(self.info, "union has no branches")
  662. for v in self.variants:
  663. v.check(schema)
  664. # Union names must match enum values; alternate names are
  665. # checked separately. Use 'seen' to tell the two apart.
  666. if seen:
  667. if v.name not in tag_member.type.member_names():
  668. raise QAPISemError(
  669. self.info,
  670. "branch '%s' is not a value of %s"
  671. % (v.name, tag_member.type.describe()))
  672. if not isinstance(v.type, QAPISchemaObjectType):
  673. raise QAPISemError(
  674. self.info,
  675. "%s cannot use %s"
  676. % (v.describe(self.info), v.type.describe()))
  677. v.type.check(schema)
  678. def check_clash(
  679. self,
  680. info: Optional[QAPISourceInfo],
  681. seen: Dict[str, QAPISchemaMember],
  682. ) -> None:
  683. for v in self.variants:
  684. # Reset seen map for each variant, since qapi names from one
  685. # branch do not affect another branch.
  686. #
  687. # v.type's typing is enforced in check() above.
  688. assert isinstance(v.type, QAPISchemaObjectType)
  689. v.type.check_clash(info, dict(seen))
  690. class QAPISchemaAlternatives(QAPISchemaVariants):
  691. def __init__(self,
  692. info: QAPISourceInfo,
  693. variants: List[QAPISchemaVariant],
  694. tag_member: QAPISchemaObjectTypeMember):
  695. super().__init__(info, variants)
  696. self.tag_member = tag_member
  697. def check(
  698. self, schema: QAPISchema, seen: Dict[str, QAPISchemaMember]
  699. ) -> None:
  700. super().check(schema, seen)
  701. assert isinstance(self.tag_member.type, QAPISchemaEnumType)
  702. assert not self.tag_member.optional
  703. assert not self.tag_member.ifcond.is_present()
  704. class QAPISchemaMember:
  705. """ Represents object members, enum members and features """
  706. role = 'member'
  707. def __init__(
  708. self,
  709. name: str,
  710. info: Optional[QAPISourceInfo],
  711. ifcond: Optional[QAPISchemaIfCond] = None,
  712. ):
  713. self.name = name
  714. self.info = info
  715. self.ifcond = ifcond or QAPISchemaIfCond()
  716. self.defined_in: Optional[str] = None
  717. def set_defined_in(self, name: str) -> None:
  718. assert not self.defined_in
  719. self.defined_in = name
  720. def check_clash(
  721. self,
  722. info: Optional[QAPISourceInfo],
  723. seen: Dict[str, QAPISchemaMember],
  724. ) -> None:
  725. cname = c_name(self.name)
  726. if cname in seen:
  727. raise QAPISemError(
  728. info,
  729. "%s collides with %s"
  730. % (self.describe(info), seen[cname].describe(info)))
  731. seen[cname] = self
  732. def connect_doc(self, doc: Optional[QAPIDoc]) -> None:
  733. if doc:
  734. doc.connect_member(self)
  735. def describe(self, info: Optional[QAPISourceInfo]) -> str:
  736. role = self.role
  737. meta = 'type'
  738. defined_in = self.defined_in
  739. assert defined_in
  740. if defined_in.startswith('q_obj_'):
  741. # See QAPISchema._make_implicit_object_type() - reverse the
  742. # mapping there to create a nice human-readable description
  743. defined_in = defined_in[6:]
  744. if defined_in.endswith('-arg'):
  745. # Implicit type created for a command's dict 'data'
  746. assert role == 'member'
  747. role = 'parameter'
  748. meta = 'command'
  749. defined_in = defined_in[:-4]
  750. elif defined_in.endswith('-base'):
  751. # Implicit type created for a union's dict 'base'
  752. role = 'base ' + role
  753. defined_in = defined_in[:-5]
  754. else:
  755. assert False
  756. assert info is not None
  757. if defined_in != info.defn_name:
  758. return "%s '%s' of %s '%s'" % (role, self.name, meta, defined_in)
  759. return "%s '%s'" % (role, self.name)
  760. class QAPISchemaEnumMember(QAPISchemaMember):
  761. role = 'value'
  762. def __init__(
  763. self,
  764. name: str,
  765. info: Optional[QAPISourceInfo],
  766. ifcond: Optional[QAPISchemaIfCond] = None,
  767. features: Optional[List[QAPISchemaFeature]] = None,
  768. ):
  769. super().__init__(name, info, ifcond)
  770. for f in features or []:
  771. f.set_defined_in(name)
  772. self.features = features or []
  773. def connect_doc(self, doc: Optional[QAPIDoc]) -> None:
  774. super().connect_doc(doc)
  775. if doc:
  776. for f in self.features:
  777. doc.connect_feature(f)
  778. class QAPISchemaFeature(QAPISchemaMember):
  779. role = 'feature'
  780. def is_special(self) -> bool:
  781. return self.name in ('deprecated', 'unstable')
  782. class QAPISchemaObjectTypeMember(QAPISchemaMember):
  783. def __init__(
  784. self,
  785. name: str,
  786. info: QAPISourceInfo,
  787. typ: str,
  788. optional: bool,
  789. ifcond: Optional[QAPISchemaIfCond] = None,
  790. features: Optional[List[QAPISchemaFeature]] = None,
  791. ):
  792. super().__init__(name, info, ifcond)
  793. for f in features or []:
  794. f.set_defined_in(name)
  795. self._type_name = typ
  796. self.type: QAPISchemaType # set during check()
  797. self.optional = optional
  798. self.features = features or []
  799. def need_has(self) -> bool:
  800. return self.optional and self.type.need_has_if_optional()
  801. def check(self, schema: QAPISchema) -> None:
  802. assert self.defined_in
  803. self.type = schema.resolve_type(self._type_name, self.info,
  804. self.describe)
  805. seen: Dict[str, QAPISchemaMember] = {}
  806. for f in self.features:
  807. f.check_clash(self.info, seen)
  808. def connect_doc(self, doc: Optional[QAPIDoc]) -> None:
  809. super().connect_doc(doc)
  810. if doc:
  811. for f in self.features:
  812. doc.connect_feature(f)
  813. class QAPISchemaVariant(QAPISchemaObjectTypeMember):
  814. role = 'branch'
  815. def __init__(
  816. self,
  817. name: str,
  818. info: QAPISourceInfo,
  819. typ: str,
  820. ifcond: QAPISchemaIfCond,
  821. ):
  822. super().__init__(name, info, typ, False, ifcond)
  823. class QAPISchemaCommand(QAPISchemaDefinition):
  824. meta = 'command'
  825. def __init__(
  826. self,
  827. name: str,
  828. info: QAPISourceInfo,
  829. doc: Optional[QAPIDoc],
  830. ifcond: QAPISchemaIfCond,
  831. features: List[QAPISchemaFeature],
  832. arg_type: Optional[str],
  833. ret_type: Optional[str],
  834. gen: bool,
  835. success_response: bool,
  836. boxed: bool,
  837. allow_oob: bool,
  838. allow_preconfig: bool,
  839. coroutine: bool,
  840. ):
  841. super().__init__(name, info, doc, ifcond, features)
  842. self._arg_type_name = arg_type
  843. self.arg_type: Optional[QAPISchemaObjectType] = None
  844. self._ret_type_name = ret_type
  845. self.ret_type: Optional[QAPISchemaType] = None
  846. self.gen = gen
  847. self.success_response = success_response
  848. self.boxed = boxed
  849. self.allow_oob = allow_oob
  850. self.allow_preconfig = allow_preconfig
  851. self.coroutine = coroutine
  852. def check(self, schema: QAPISchema) -> None:
  853. assert self.info is not None
  854. super().check(schema)
  855. if self._arg_type_name:
  856. arg_type = schema.resolve_type(
  857. self._arg_type_name, self.info, "command's 'data'")
  858. if not isinstance(arg_type, QAPISchemaObjectType):
  859. raise QAPISemError(
  860. self.info,
  861. "command's 'data' cannot take %s"
  862. % arg_type.describe())
  863. self.arg_type = arg_type
  864. if self.arg_type.branches and not self.boxed:
  865. raise QAPISemError(
  866. self.info,
  867. "command's 'data' can take %s only with 'boxed': true"
  868. % self.arg_type.describe())
  869. self.arg_type.check(schema)
  870. if self.arg_type.has_conditional_members() and not self.boxed:
  871. raise QAPISemError(
  872. self.info,
  873. "conditional command arguments require 'boxed': true")
  874. if self._ret_type_name:
  875. self.ret_type = schema.resolve_type(
  876. self._ret_type_name, self.info, "command's 'returns'")
  877. if self.name not in self.info.pragma.command_returns_exceptions:
  878. typ = self.ret_type
  879. if isinstance(typ, QAPISchemaArrayType):
  880. typ = typ.element_type
  881. if not isinstance(typ, QAPISchemaObjectType):
  882. raise QAPISemError(
  883. self.info,
  884. "command's 'returns' cannot take %s"
  885. % self.ret_type.describe())
  886. def connect_doc(self, doc: Optional[QAPIDoc] = None) -> None:
  887. super().connect_doc(doc)
  888. doc = doc or self.doc
  889. if doc:
  890. if self.arg_type and self.arg_type.is_implicit():
  891. self.arg_type.connect_doc(doc)
  892. def visit(self, visitor: QAPISchemaVisitor) -> None:
  893. super().visit(visitor)
  894. visitor.visit_command(
  895. self.name, self.info, self.ifcond, self.features,
  896. self.arg_type, self.ret_type, self.gen, self.success_response,
  897. self.boxed, self.allow_oob, self.allow_preconfig,
  898. self.coroutine)
  899. class QAPISchemaEvent(QAPISchemaDefinition):
  900. meta = 'event'
  901. def __init__(
  902. self,
  903. name: str,
  904. info: QAPISourceInfo,
  905. doc: Optional[QAPIDoc],
  906. ifcond: QAPISchemaIfCond,
  907. features: List[QAPISchemaFeature],
  908. arg_type: Optional[str],
  909. boxed: bool,
  910. ):
  911. super().__init__(name, info, doc, ifcond, features)
  912. self._arg_type_name = arg_type
  913. self.arg_type: Optional[QAPISchemaObjectType] = None
  914. self.boxed = boxed
  915. def check(self, schema: QAPISchema) -> None:
  916. super().check(schema)
  917. if self._arg_type_name:
  918. typ = schema.resolve_type(
  919. self._arg_type_name, self.info, "event's 'data'")
  920. if not isinstance(typ, QAPISchemaObjectType):
  921. raise QAPISemError(
  922. self.info,
  923. "event's 'data' cannot take %s"
  924. % typ.describe())
  925. self.arg_type = typ
  926. if self.arg_type.branches and not self.boxed:
  927. raise QAPISemError(
  928. self.info,
  929. "event's 'data' can take %s only with 'boxed': true"
  930. % self.arg_type.describe())
  931. self.arg_type.check(schema)
  932. if self.arg_type.has_conditional_members() and not self.boxed:
  933. raise QAPISemError(
  934. self.info,
  935. "conditional event arguments require 'boxed': true")
  936. def connect_doc(self, doc: Optional[QAPIDoc] = None) -> None:
  937. super().connect_doc(doc)
  938. doc = doc or self.doc
  939. if doc:
  940. if self.arg_type and self.arg_type.is_implicit():
  941. self.arg_type.connect_doc(doc)
  942. def visit(self, visitor: QAPISchemaVisitor) -> None:
  943. super().visit(visitor)
  944. visitor.visit_event(
  945. self.name, self.info, self.ifcond, self.features,
  946. self.arg_type, self.boxed)
  947. class QAPISchema:
  948. def __init__(self, fname: str):
  949. self.fname = fname
  950. try:
  951. parser = QAPISchemaParser(fname)
  952. except OSError as err:
  953. raise QAPIError(
  954. f"can't read schema file '{fname}': {err.strerror}"
  955. ) from err
  956. exprs = check_exprs(parser.exprs)
  957. self.docs = parser.docs
  958. self._entity_list: List[QAPISchemaEntity] = []
  959. self._entity_dict: Dict[str, QAPISchemaDefinition] = {}
  960. self._module_dict: Dict[str, QAPISchemaModule] = OrderedDict()
  961. self._schema_dir = os.path.dirname(fname)
  962. self._make_module(QAPISchemaModule.BUILTIN_MODULE_NAME)
  963. self._make_module(fname)
  964. self._predefining = True
  965. self._def_predefineds()
  966. self._predefining = False
  967. self._def_exprs(exprs)
  968. self.check()
  969. def _def_entity(self, ent: QAPISchemaEntity) -> None:
  970. self._entity_list.append(ent)
  971. def _def_definition(self, defn: QAPISchemaDefinition) -> None:
  972. # Only the predefined types are allowed to not have info
  973. assert defn.info or self._predefining
  974. self._def_entity(defn)
  975. # TODO reject names that differ only in '_' vs. '.' vs. '-',
  976. # because they're liable to clash in generated C.
  977. other_defn = self._entity_dict.get(defn.name)
  978. if other_defn:
  979. if other_defn.info:
  980. where = QAPISourceError(other_defn.info, "previous definition")
  981. raise QAPISemError(
  982. defn.info,
  983. "'%s' is already defined\n%s" % (defn.name, where))
  984. raise QAPISemError(
  985. defn.info, "%s is already defined" % other_defn.describe())
  986. self._entity_dict[defn.name] = defn
  987. def lookup_entity(self, name: str) -> Optional[QAPISchemaEntity]:
  988. return self._entity_dict.get(name)
  989. def lookup_type(self, name: str) -> Optional[QAPISchemaType]:
  990. typ = self.lookup_entity(name)
  991. if isinstance(typ, QAPISchemaType):
  992. return typ
  993. return None
  994. def resolve_type(
  995. self,
  996. name: str,
  997. info: Optional[QAPISourceInfo],
  998. what: Union[None, str, Callable[[QAPISourceInfo], str]],
  999. ) -> QAPISchemaType:
  1000. typ = self.lookup_type(name)
  1001. if not typ:
  1002. assert info and what # built-in types must not fail lookup
  1003. if callable(what):
  1004. what = what(info)
  1005. raise QAPISemError(
  1006. info, "%s uses unknown type '%s'" % (what, name))
  1007. return typ
  1008. def _module_name(self, fname: str) -> str:
  1009. if QAPISchemaModule.is_system_module(fname):
  1010. return fname
  1011. return os.path.relpath(fname, self._schema_dir)
  1012. def _make_module(self, fname: str) -> QAPISchemaModule:
  1013. name = self._module_name(fname)
  1014. if name not in self._module_dict:
  1015. self._module_dict[name] = QAPISchemaModule(name)
  1016. return self._module_dict[name]
  1017. def module_by_fname(self, fname: str) -> QAPISchemaModule:
  1018. name = self._module_name(fname)
  1019. return self._module_dict[name]
  1020. def _def_include(self, expr: QAPIExpression) -> None:
  1021. include = expr['include']
  1022. assert expr.doc is None
  1023. self._def_entity(
  1024. QAPISchemaInclude(self._make_module(include), expr.info))
  1025. def _def_builtin_type(
  1026. self, name: str, json_type: str, c_type: str
  1027. ) -> None:
  1028. self._def_definition(QAPISchemaBuiltinType(name, json_type, c_type))
  1029. # Instantiating only the arrays that are actually used would
  1030. # be nice, but we can't as long as their generated code
  1031. # (qapi-builtin-types.[ch]) may be shared by some other
  1032. # schema.
  1033. self._make_array_type(name, None)
  1034. def _def_predefineds(self) -> None:
  1035. for t in [('str', 'string', 'char' + POINTER_SUFFIX),
  1036. ('number', 'number', 'double'),
  1037. ('int', 'int', 'int64_t'),
  1038. ('int8', 'int', 'int8_t'),
  1039. ('int16', 'int', 'int16_t'),
  1040. ('int32', 'int', 'int32_t'),
  1041. ('int64', 'int', 'int64_t'),
  1042. ('uint8', 'int', 'uint8_t'),
  1043. ('uint16', 'int', 'uint16_t'),
  1044. ('uint32', 'int', 'uint32_t'),
  1045. ('uint64', 'int', 'uint64_t'),
  1046. ('size', 'int', 'uint64_t'),
  1047. ('bool', 'boolean', 'bool'),
  1048. ('any', 'value', 'QObject' + POINTER_SUFFIX),
  1049. ('null', 'null', 'QNull' + POINTER_SUFFIX)]:
  1050. self._def_builtin_type(*t)
  1051. self.the_empty_object_type = QAPISchemaObjectType(
  1052. 'q_empty', None, None, None, None, None, [], None)
  1053. self._def_definition(self.the_empty_object_type)
  1054. qtypes = ['none', 'qnull', 'qnum', 'qstring', 'qdict', 'qlist',
  1055. 'qbool']
  1056. qtype_values = self._make_enum_members(
  1057. [{'name': n} for n in qtypes], None)
  1058. self._def_definition(QAPISchemaEnumType(
  1059. 'QType', None, None, None, None, qtype_values, None))
  1060. def _make_features(
  1061. self,
  1062. features: Optional[List[Dict[str, Any]]],
  1063. info: Optional[QAPISourceInfo],
  1064. ) -> List[QAPISchemaFeature]:
  1065. if features is None:
  1066. return []
  1067. return [QAPISchemaFeature(f['name'], info,
  1068. QAPISchemaIfCond(f.get('if')))
  1069. for f in features]
  1070. def _make_enum_member(
  1071. self,
  1072. name: str,
  1073. ifcond: Optional[Union[str, Dict[str, Any]]],
  1074. features: Optional[List[Dict[str, Any]]],
  1075. info: Optional[QAPISourceInfo],
  1076. ) -> QAPISchemaEnumMember:
  1077. return QAPISchemaEnumMember(name, info,
  1078. QAPISchemaIfCond(ifcond),
  1079. self._make_features(features, info))
  1080. def _make_enum_members(
  1081. self, values: List[Dict[str, Any]], info: Optional[QAPISourceInfo]
  1082. ) -> List[QAPISchemaEnumMember]:
  1083. return [self._make_enum_member(v['name'], v.get('if'),
  1084. v.get('features'), info)
  1085. for v in values]
  1086. def _make_array_type(
  1087. self, element_type: str, info: Optional[QAPISourceInfo]
  1088. ) -> str:
  1089. name = element_type + 'List' # reserved by check_defn_name_str()
  1090. if not self.lookup_type(name):
  1091. self._def_definition(QAPISchemaArrayType(
  1092. name, info, element_type))
  1093. return name
  1094. def _make_implicit_object_type(
  1095. self,
  1096. name: str,
  1097. info: QAPISourceInfo,
  1098. ifcond: QAPISchemaIfCond,
  1099. role: str,
  1100. members: List[QAPISchemaObjectTypeMember],
  1101. ) -> Optional[str]:
  1102. if not members:
  1103. return None
  1104. # See also QAPISchemaObjectTypeMember.describe()
  1105. name = 'q_obj_%s-%s' % (name, role)
  1106. typ = self.lookup_entity(name)
  1107. if typ:
  1108. assert isinstance(typ, QAPISchemaObjectType)
  1109. # The implicit object type has multiple users. This can
  1110. # only be a duplicate definition, which will be flagged
  1111. # later.
  1112. else:
  1113. self._def_definition(QAPISchemaObjectType(
  1114. name, info, None, ifcond, None, None, members, None))
  1115. return name
  1116. def _def_enum_type(self, expr: QAPIExpression) -> None:
  1117. name = expr['enum']
  1118. data = expr['data']
  1119. prefix = expr.get('prefix')
  1120. ifcond = QAPISchemaIfCond(expr.get('if'))
  1121. info = expr.info
  1122. features = self._make_features(expr.get('features'), info)
  1123. self._def_definition(QAPISchemaEnumType(
  1124. name, info, expr.doc, ifcond, features,
  1125. self._make_enum_members(data, info), prefix))
  1126. def _make_member(
  1127. self,
  1128. name: str,
  1129. typ: Union[List[str], str],
  1130. ifcond: QAPISchemaIfCond,
  1131. features: Optional[List[Dict[str, Any]]],
  1132. info: QAPISourceInfo,
  1133. ) -> QAPISchemaObjectTypeMember:
  1134. optional = False
  1135. if name.startswith('*'):
  1136. name = name[1:]
  1137. optional = True
  1138. if isinstance(typ, list):
  1139. assert len(typ) == 1
  1140. typ = self._make_array_type(typ[0], info)
  1141. return QAPISchemaObjectTypeMember(name, info, typ, optional, ifcond,
  1142. self._make_features(features, info))
  1143. def _make_members(
  1144. self,
  1145. data: Dict[str, Any],
  1146. info: QAPISourceInfo,
  1147. ) -> List[QAPISchemaObjectTypeMember]:
  1148. return [self._make_member(key, value['type'],
  1149. QAPISchemaIfCond(value.get('if')),
  1150. value.get('features'), info)
  1151. for (key, value) in data.items()]
  1152. def _def_struct_type(self, expr: QAPIExpression) -> None:
  1153. name = expr['struct']
  1154. base = expr.get('base')
  1155. data = expr['data']
  1156. info = expr.info
  1157. ifcond = QAPISchemaIfCond(expr.get('if'))
  1158. features = self._make_features(expr.get('features'), info)
  1159. self._def_definition(QAPISchemaObjectType(
  1160. name, info, expr.doc, ifcond, features, base,
  1161. self._make_members(data, info),
  1162. None))
  1163. def _make_variant(
  1164. self,
  1165. case: str,
  1166. typ: str,
  1167. ifcond: QAPISchemaIfCond,
  1168. info: QAPISourceInfo,
  1169. ) -> QAPISchemaVariant:
  1170. if isinstance(typ, list):
  1171. assert len(typ) == 1
  1172. typ = self._make_array_type(typ[0], info)
  1173. return QAPISchemaVariant(case, info, typ, ifcond)
  1174. def _def_union_type(self, expr: QAPIExpression) -> None:
  1175. name = expr['union']
  1176. base = expr['base']
  1177. tag_name = expr['discriminator']
  1178. data = expr['data']
  1179. assert isinstance(data, dict)
  1180. info = expr.info
  1181. ifcond = QAPISchemaIfCond(expr.get('if'))
  1182. features = self._make_features(expr.get('features'), info)
  1183. if isinstance(base, dict):
  1184. base = self._make_implicit_object_type(
  1185. name, info, ifcond,
  1186. 'base', self._make_members(base, info))
  1187. variants = [
  1188. self._make_variant(key, value['type'],
  1189. QAPISchemaIfCond(value.get('if')),
  1190. info)
  1191. for (key, value) in data.items()]
  1192. members: List[QAPISchemaObjectTypeMember] = []
  1193. self._def_definition(
  1194. QAPISchemaObjectType(name, info, expr.doc, ifcond, features,
  1195. base, members,
  1196. QAPISchemaBranches(
  1197. info, variants, tag_name)))
  1198. def _def_alternate_type(self, expr: QAPIExpression) -> None:
  1199. name = expr['alternate']
  1200. data = expr['data']
  1201. assert isinstance(data, dict)
  1202. ifcond = QAPISchemaIfCond(expr.get('if'))
  1203. info = expr.info
  1204. features = self._make_features(expr.get('features'), info)
  1205. variants = [
  1206. self._make_variant(key, value['type'],
  1207. QAPISchemaIfCond(value.get('if')),
  1208. info)
  1209. for (key, value) in data.items()]
  1210. tag_member = QAPISchemaObjectTypeMember('type', info, 'QType', False)
  1211. self._def_definition(
  1212. QAPISchemaAlternateType(
  1213. name, info, expr.doc, ifcond, features,
  1214. QAPISchemaAlternatives(info, variants, tag_member)))
  1215. def _def_command(self, expr: QAPIExpression) -> None:
  1216. name = expr['command']
  1217. data = expr.get('data')
  1218. rets = expr.get('returns')
  1219. gen = expr.get('gen', True)
  1220. success_response = expr.get('success-response', True)
  1221. boxed = expr.get('boxed', False)
  1222. allow_oob = expr.get('allow-oob', False)
  1223. allow_preconfig = expr.get('allow-preconfig', False)
  1224. coroutine = expr.get('coroutine', False)
  1225. ifcond = QAPISchemaIfCond(expr.get('if'))
  1226. info = expr.info
  1227. features = self._make_features(expr.get('features'), info)
  1228. if isinstance(data, OrderedDict):
  1229. data = self._make_implicit_object_type(
  1230. name, info, ifcond,
  1231. 'arg', self._make_members(data, info))
  1232. if isinstance(rets, list):
  1233. assert len(rets) == 1
  1234. rets = self._make_array_type(rets[0], info)
  1235. self._def_definition(
  1236. QAPISchemaCommand(name, info, expr.doc, ifcond, features, data,
  1237. rets, gen, success_response, boxed, allow_oob,
  1238. allow_preconfig, coroutine))
  1239. def _def_event(self, expr: QAPIExpression) -> None:
  1240. name = expr['event']
  1241. data = expr.get('data')
  1242. boxed = expr.get('boxed', False)
  1243. ifcond = QAPISchemaIfCond(expr.get('if'))
  1244. info = expr.info
  1245. features = self._make_features(expr.get('features'), info)
  1246. if isinstance(data, OrderedDict):
  1247. data = self._make_implicit_object_type(
  1248. name, info, ifcond,
  1249. 'arg', self._make_members(data, info))
  1250. self._def_definition(QAPISchemaEvent(name, info, expr.doc, ifcond,
  1251. features, data, boxed))
  1252. def _def_exprs(self, exprs: List[QAPIExpression]) -> None:
  1253. for expr in exprs:
  1254. if 'enum' in expr:
  1255. self._def_enum_type(expr)
  1256. elif 'struct' in expr:
  1257. self._def_struct_type(expr)
  1258. elif 'union' in expr:
  1259. self._def_union_type(expr)
  1260. elif 'alternate' in expr:
  1261. self._def_alternate_type(expr)
  1262. elif 'command' in expr:
  1263. self._def_command(expr)
  1264. elif 'event' in expr:
  1265. self._def_event(expr)
  1266. elif 'include' in expr:
  1267. self._def_include(expr)
  1268. else:
  1269. assert False
  1270. def check(self) -> None:
  1271. for ent in self._entity_list:
  1272. ent.check(self)
  1273. ent.connect_doc()
  1274. for ent in self._entity_list:
  1275. ent.set_module(self)
  1276. for doc in self.docs:
  1277. doc.check()
  1278. def visit(self, visitor: QAPISchemaVisitor) -> None:
  1279. visitor.visit_begin(self)
  1280. for mod in self._module_dict.values():
  1281. mod.visit(visitor)
  1282. visitor.visit_end()