2
0

schema.py 51 KB

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