schema.py 50 KB

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