schema.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043
  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. # TODO catching name collisions in generated code would be nice
  15. import os
  16. import re
  17. from collections import OrderedDict
  18. from qapi.common import c_name, pointer_suffix
  19. from qapi.error import QAPIError, QAPIParseError, QAPISemError
  20. from qapi.expr import check_exprs
  21. from qapi.parser import QAPISchemaParser
  22. class QAPISchemaEntity(object):
  23. meta = None
  24. def __init__(self, name, info, doc, ifcond=None):
  25. assert name is None or isinstance(name, str)
  26. self.name = name
  27. self._module = None
  28. # For explicitly defined entities, info points to the (explicit)
  29. # definition. For builtins (and their arrays), info is None.
  30. # For implicitly defined entities, info points to a place that
  31. # triggered the implicit definition (there may be more than one
  32. # such place).
  33. self.info = info
  34. self.doc = doc
  35. self._ifcond = ifcond or []
  36. self._checked = False
  37. def c_name(self):
  38. return c_name(self.name)
  39. def check(self, schema):
  40. assert not self._checked
  41. if self.info:
  42. self._module = os.path.relpath(self.info.fname,
  43. os.path.dirname(schema.fname))
  44. self._checked = True
  45. @property
  46. def ifcond(self):
  47. assert self._checked
  48. return self._ifcond
  49. @property
  50. def module(self):
  51. assert self._checked
  52. return self._module
  53. def is_implicit(self):
  54. return not self.info
  55. def visit(self, visitor):
  56. assert self._checked
  57. def describe(self):
  58. assert self.meta
  59. return "%s '%s'" % (self.meta, self.name)
  60. class QAPISchemaVisitor(object):
  61. def visit_begin(self, schema):
  62. pass
  63. def visit_end(self):
  64. pass
  65. def visit_module(self, fname):
  66. pass
  67. def visit_needed(self, entity):
  68. # Default to visiting everything
  69. return True
  70. def visit_include(self, fname, info):
  71. pass
  72. def visit_builtin_type(self, name, info, json_type):
  73. pass
  74. def visit_enum_type(self, name, info, ifcond, members, prefix):
  75. pass
  76. def visit_array_type(self, name, info, ifcond, element_type):
  77. pass
  78. def visit_object_type(self, name, info, ifcond, base, members, variants,
  79. features):
  80. pass
  81. def visit_object_type_flat(self, name, info, ifcond, members, variants,
  82. features):
  83. pass
  84. def visit_alternate_type(self, name, info, ifcond, variants):
  85. pass
  86. def visit_command(self, name, info, ifcond, arg_type, ret_type, gen,
  87. success_response, boxed, allow_oob, allow_preconfig):
  88. pass
  89. def visit_event(self, name, info, ifcond, arg_type, boxed):
  90. pass
  91. class QAPISchemaInclude(QAPISchemaEntity):
  92. def __init__(self, fname, info):
  93. QAPISchemaEntity.__init__(self, None, info, None)
  94. self.fname = fname
  95. def visit(self, visitor):
  96. QAPISchemaEntity.visit(self, visitor)
  97. visitor.visit_include(self.fname, self.info)
  98. class QAPISchemaType(QAPISchemaEntity):
  99. # Return the C type for common use.
  100. # For the types we commonly box, this is a pointer type.
  101. def c_type(self):
  102. pass
  103. # Return the C type to be used in a parameter list.
  104. def c_param_type(self):
  105. return self.c_type()
  106. # Return the C type to be used where we suppress boxing.
  107. def c_unboxed_type(self):
  108. return self.c_type()
  109. def json_type(self):
  110. pass
  111. def alternate_qtype(self):
  112. json2qtype = {
  113. 'null': 'QTYPE_QNULL',
  114. 'string': 'QTYPE_QSTRING',
  115. 'number': 'QTYPE_QNUM',
  116. 'int': 'QTYPE_QNUM',
  117. 'boolean': 'QTYPE_QBOOL',
  118. 'object': 'QTYPE_QDICT'
  119. }
  120. return json2qtype.get(self.json_type())
  121. def doc_type(self):
  122. if self.is_implicit():
  123. return None
  124. return self.name
  125. def describe(self):
  126. assert self.meta
  127. return "%s type '%s'" % (self.meta, self.name)
  128. class QAPISchemaBuiltinType(QAPISchemaType):
  129. meta = 'built-in'
  130. def __init__(self, name, json_type, c_type):
  131. QAPISchemaType.__init__(self, name, None, None)
  132. assert not c_type or isinstance(c_type, str)
  133. assert json_type in ('string', 'number', 'int', 'boolean', 'null',
  134. 'value')
  135. self._json_type_name = json_type
  136. self._c_type_name = c_type
  137. def c_name(self):
  138. return self.name
  139. def c_type(self):
  140. return self._c_type_name
  141. def c_param_type(self):
  142. if self.name == 'str':
  143. return 'const ' + self._c_type_name
  144. return self._c_type_name
  145. def json_type(self):
  146. return self._json_type_name
  147. def doc_type(self):
  148. return self.json_type()
  149. def visit(self, visitor):
  150. QAPISchemaType.visit(self, visitor)
  151. visitor.visit_builtin_type(self.name, self.info, self.json_type())
  152. class QAPISchemaEnumType(QAPISchemaType):
  153. meta = 'enum'
  154. def __init__(self, name, info, doc, ifcond, members, prefix):
  155. QAPISchemaType.__init__(self, name, info, doc, ifcond)
  156. for m in members:
  157. assert isinstance(m, QAPISchemaEnumMember)
  158. m.set_defined_in(name)
  159. assert prefix is None or isinstance(prefix, str)
  160. self.members = members
  161. self.prefix = prefix
  162. def check(self, schema):
  163. QAPISchemaType.check(self, schema)
  164. seen = {}
  165. for m in self.members:
  166. m.check_clash(self.info, seen)
  167. if self.doc:
  168. self.doc.connect_member(m)
  169. def is_implicit(self):
  170. # See QAPISchema._make_implicit_enum_type() and ._def_predefineds()
  171. return self.name.endswith('Kind') or self.name == 'QType'
  172. def c_type(self):
  173. return c_name(self.name)
  174. def member_names(self):
  175. return [m.name for m in self.members]
  176. def json_type(self):
  177. return 'string'
  178. def visit(self, visitor):
  179. QAPISchemaType.visit(self, visitor)
  180. visitor.visit_enum_type(self.name, self.info, self.ifcond,
  181. self.members, self.prefix)
  182. class QAPISchemaArrayType(QAPISchemaType):
  183. meta = 'array'
  184. def __init__(self, name, info, element_type):
  185. QAPISchemaType.__init__(self, name, info, None, None)
  186. assert isinstance(element_type, str)
  187. self._element_type_name = element_type
  188. self.element_type = None
  189. def check(self, schema):
  190. QAPISchemaType.check(self, schema)
  191. self.element_type = schema.resolve_type(
  192. self._element_type_name, self.info,
  193. self.info and self.info.defn_meta)
  194. assert not isinstance(self.element_type, QAPISchemaArrayType)
  195. @property
  196. def ifcond(self):
  197. assert self._checked
  198. return self.element_type.ifcond
  199. @property
  200. def module(self):
  201. assert self._checked
  202. return self.element_type.module
  203. def is_implicit(self):
  204. return True
  205. def c_type(self):
  206. return c_name(self.name) + pointer_suffix
  207. def json_type(self):
  208. return 'array'
  209. def doc_type(self):
  210. elt_doc_type = self.element_type.doc_type()
  211. if not elt_doc_type:
  212. return None
  213. return 'array of ' + elt_doc_type
  214. def visit(self, visitor):
  215. QAPISchemaType.visit(self, visitor)
  216. visitor.visit_array_type(self.name, self.info, self.ifcond,
  217. self.element_type)
  218. def describe(self):
  219. assert self.meta
  220. return "%s type ['%s']" % (self.meta, self._element_type_name)
  221. class QAPISchemaObjectType(QAPISchemaType):
  222. def __init__(self, name, info, doc, ifcond,
  223. base, local_members, variants, features):
  224. # struct has local_members, optional base, and no variants
  225. # flat union has base, variants, and no local_members
  226. # simple union has local_members, variants, and no base
  227. QAPISchemaType.__init__(self, name, info, doc, ifcond)
  228. self.meta = 'union' if variants else 'struct'
  229. assert base is None or isinstance(base, str)
  230. for m in local_members:
  231. assert isinstance(m, QAPISchemaObjectTypeMember)
  232. m.set_defined_in(name)
  233. if variants is not None:
  234. assert isinstance(variants, QAPISchemaObjectTypeVariants)
  235. variants.set_defined_in(name)
  236. for f in features:
  237. assert isinstance(f, QAPISchemaFeature)
  238. f.set_defined_in(name)
  239. self._base_name = base
  240. self.base = None
  241. self.local_members = local_members
  242. self.variants = variants
  243. self.members = None
  244. self.features = features
  245. def check(self, schema):
  246. # This calls another type T's .check() exactly when the C
  247. # struct emitted by gen_object() contains that T's C struct
  248. # (pointers don't count).
  249. if self.members is not None:
  250. # A previous .check() completed: nothing to do
  251. return
  252. if self._checked:
  253. # Recursed: C struct contains itself
  254. raise QAPISemError(self.info,
  255. "object %s contains itself" % self.name)
  256. QAPISchemaType.check(self, schema)
  257. assert self._checked and self.members is None
  258. seen = OrderedDict()
  259. if self._base_name:
  260. self.base = schema.resolve_type(self._base_name, self.info,
  261. "'base'")
  262. if (not isinstance(self.base, QAPISchemaObjectType)
  263. or self.base.variants):
  264. raise QAPISemError(
  265. self.info,
  266. "'base' requires a struct type, %s isn't"
  267. % self.base.describe())
  268. self.base.check(schema)
  269. self.base.check_clash(self.info, seen)
  270. for m in self.local_members:
  271. m.check(schema)
  272. m.check_clash(self.info, seen)
  273. if self.doc:
  274. self.doc.connect_member(m)
  275. members = seen.values()
  276. if self.variants:
  277. self.variants.check(schema, seen)
  278. self.variants.check_clash(self.info, seen)
  279. # Features are in a name space separate from members
  280. seen = {}
  281. for f in self.features:
  282. f.check_clash(self.info, seen)
  283. if self.doc:
  284. self.doc.check()
  285. self.members = members # mark completed
  286. # Check that the members of this type do not cause duplicate JSON members,
  287. # and update seen to track the members seen so far. Report any errors
  288. # on behalf of info, which is not necessarily self.info
  289. def check_clash(self, info, seen):
  290. assert self._checked
  291. assert not self.variants # not implemented
  292. for m in self.members:
  293. m.check_clash(info, seen)
  294. @property
  295. def ifcond(self):
  296. assert self._checked
  297. if isinstance(self._ifcond, QAPISchemaType):
  298. # Simple union wrapper type inherits from wrapped type;
  299. # see _make_implicit_object_type()
  300. return self._ifcond.ifcond
  301. return self._ifcond
  302. def is_implicit(self):
  303. # See QAPISchema._make_implicit_object_type(), as well as
  304. # _def_predefineds()
  305. return self.name.startswith('q_')
  306. def is_empty(self):
  307. assert self.members is not None
  308. return not self.members and not self.variants
  309. def c_name(self):
  310. assert self.name != 'q_empty'
  311. return QAPISchemaType.c_name(self)
  312. def c_type(self):
  313. assert not self.is_implicit()
  314. return c_name(self.name) + pointer_suffix
  315. def c_unboxed_type(self):
  316. return c_name(self.name)
  317. def json_type(self):
  318. return 'object'
  319. def visit(self, visitor):
  320. QAPISchemaType.visit(self, visitor)
  321. visitor.visit_object_type(self.name, self.info, self.ifcond,
  322. self.base, self.local_members, self.variants,
  323. self.features)
  324. visitor.visit_object_type_flat(self.name, self.info, self.ifcond,
  325. self.members, self.variants,
  326. self.features)
  327. class QAPISchemaMember(object):
  328. """ Represents object members, enum members and features """
  329. role = 'member'
  330. def __init__(self, name, info, ifcond=None):
  331. assert isinstance(name, str)
  332. self.name = name
  333. self.info = info
  334. self.ifcond = ifcond or []
  335. self.defined_in = None
  336. def set_defined_in(self, name):
  337. assert not self.defined_in
  338. self.defined_in = name
  339. def check_clash(self, info, seen):
  340. cname = c_name(self.name)
  341. if cname in seen:
  342. raise QAPISemError(
  343. info,
  344. "%s collides with %s"
  345. % (self.describe(info), seen[cname].describe(info)))
  346. seen[cname] = self
  347. def describe(self, info):
  348. role = self.role
  349. defined_in = self.defined_in
  350. assert defined_in
  351. if defined_in.startswith('q_obj_'):
  352. # See QAPISchema._make_implicit_object_type() - reverse the
  353. # mapping there to create a nice human-readable description
  354. defined_in = defined_in[6:]
  355. if defined_in.endswith('-arg'):
  356. # Implicit type created for a command's dict 'data'
  357. assert role == 'member'
  358. role = 'parameter'
  359. elif defined_in.endswith('-base'):
  360. # Implicit type created for a flat union's dict 'base'
  361. role = 'base ' + role
  362. else:
  363. # Implicit type created for a simple union's branch
  364. assert defined_in.endswith('-wrapper')
  365. # Unreachable and not implemented
  366. assert False
  367. elif defined_in.endswith('Kind'):
  368. # See QAPISchema._make_implicit_enum_type()
  369. # Implicit enum created for simple union's branches
  370. assert role == 'value'
  371. role = 'branch'
  372. elif defined_in != info.defn_name:
  373. return "%s '%s' of type '%s'" % (role, self.name, defined_in)
  374. return "%s '%s'" % (role, self.name)
  375. class QAPISchemaEnumMember(QAPISchemaMember):
  376. role = 'value'
  377. class QAPISchemaFeature(QAPISchemaMember):
  378. role = 'feature'
  379. class QAPISchemaObjectTypeMember(QAPISchemaMember):
  380. def __init__(self, name, info, typ, optional, ifcond=None):
  381. QAPISchemaMember.__init__(self, name, info, ifcond)
  382. assert isinstance(typ, str)
  383. assert isinstance(optional, bool)
  384. self._type_name = typ
  385. self.type = None
  386. self.optional = optional
  387. def check(self, schema):
  388. assert self.defined_in
  389. self.type = schema.resolve_type(self._type_name, self.info,
  390. self.describe)
  391. class QAPISchemaObjectTypeVariants(object):
  392. def __init__(self, tag_name, info, tag_member, variants):
  393. # Flat unions pass tag_name but not tag_member.
  394. # Simple unions and alternates pass tag_member but not tag_name.
  395. # After check(), tag_member is always set, and tag_name remains
  396. # a reliable witness of being used by a flat union.
  397. assert bool(tag_member) != bool(tag_name)
  398. assert (isinstance(tag_name, str) or
  399. isinstance(tag_member, QAPISchemaObjectTypeMember))
  400. for v in variants:
  401. assert isinstance(v, QAPISchemaObjectTypeVariant)
  402. self._tag_name = tag_name
  403. self.info = info
  404. self.tag_member = tag_member
  405. self.variants = variants
  406. def set_defined_in(self, name):
  407. for v in self.variants:
  408. v.set_defined_in(name)
  409. def check(self, schema, seen):
  410. if not self.tag_member: # flat union
  411. self.tag_member = seen.get(c_name(self._tag_name))
  412. base = "'base'"
  413. # Pointing to the base type when not implicit would be
  414. # nice, but we don't know it here
  415. if not self.tag_member or self._tag_name != self.tag_member.name:
  416. raise QAPISemError(
  417. self.info,
  418. "discriminator '%s' is not a member of %s"
  419. % (self._tag_name, base))
  420. # Here we do:
  421. base_type = schema.lookup_type(self.tag_member.defined_in)
  422. assert base_type
  423. if not base_type.is_implicit():
  424. base = "base type '%s'" % self.tag_member.defined_in
  425. if not isinstance(self.tag_member.type, QAPISchemaEnumType):
  426. raise QAPISemError(
  427. self.info,
  428. "discriminator member '%s' of %s must be of enum type"
  429. % (self._tag_name, base))
  430. if self.tag_member.optional:
  431. raise QAPISemError(
  432. self.info,
  433. "discriminator member '%s' of %s must not be optional"
  434. % (self._tag_name, base))
  435. if self.tag_member.ifcond:
  436. raise QAPISemError(
  437. self.info,
  438. "discriminator member '%s' of %s must not be conditional"
  439. % (self._tag_name, base))
  440. else: # simple union
  441. assert isinstance(self.tag_member.type, QAPISchemaEnumType)
  442. assert not self.tag_member.optional
  443. assert self.tag_member.ifcond == []
  444. if self._tag_name: # flat union
  445. # branches that are not explicitly covered get an empty type
  446. cases = set([v.name for v in self.variants])
  447. for m in self.tag_member.type.members:
  448. if m.name not in cases:
  449. v = QAPISchemaObjectTypeVariant(m.name, self.info,
  450. 'q_empty', m.ifcond)
  451. v.set_defined_in(self.tag_member.defined_in)
  452. self.variants.append(v)
  453. if not self.variants:
  454. raise QAPISemError(self.info, "union has no branches")
  455. for v in self.variants:
  456. v.check(schema)
  457. # Union names must match enum values; alternate names are
  458. # checked separately. Use 'seen' to tell the two apart.
  459. if seen:
  460. if v.name not in self.tag_member.type.member_names():
  461. raise QAPISemError(
  462. self.info,
  463. "branch '%s' is not a value of %s"
  464. % (v.name, self.tag_member.type.describe()))
  465. if (not isinstance(v.type, QAPISchemaObjectType)
  466. or v.type.variants):
  467. raise QAPISemError(
  468. self.info,
  469. "%s cannot use %s"
  470. % (v.describe(self.info), v.type.describe()))
  471. v.type.check(schema)
  472. def check_clash(self, info, seen):
  473. for v in self.variants:
  474. # Reset seen map for each variant, since qapi names from one
  475. # branch do not affect another branch
  476. v.type.check_clash(info, dict(seen))
  477. class QAPISchemaObjectTypeVariant(QAPISchemaObjectTypeMember):
  478. role = 'branch'
  479. def __init__(self, name, info, typ, ifcond=None):
  480. QAPISchemaObjectTypeMember.__init__(self, name, info, typ,
  481. False, ifcond)
  482. class QAPISchemaAlternateType(QAPISchemaType):
  483. meta = 'alternate'
  484. def __init__(self, name, info, doc, ifcond, variants):
  485. QAPISchemaType.__init__(self, name, info, doc, ifcond)
  486. assert isinstance(variants, QAPISchemaObjectTypeVariants)
  487. assert variants.tag_member
  488. variants.set_defined_in(name)
  489. variants.tag_member.set_defined_in(self.name)
  490. self.variants = variants
  491. def check(self, schema):
  492. QAPISchemaType.check(self, schema)
  493. self.variants.tag_member.check(schema)
  494. # Not calling self.variants.check_clash(), because there's nothing
  495. # to clash with
  496. self.variants.check(schema, {})
  497. # Alternate branch names have no relation to the tag enum values;
  498. # so we have to check for potential name collisions ourselves.
  499. seen = {}
  500. types_seen = {}
  501. for v in self.variants.variants:
  502. v.check_clash(self.info, seen)
  503. qtype = v.type.alternate_qtype()
  504. if not qtype:
  505. raise QAPISemError(
  506. self.info,
  507. "%s cannot use %s"
  508. % (v.describe(self.info), v.type.describe()))
  509. conflicting = set([qtype])
  510. if qtype == 'QTYPE_QSTRING':
  511. if isinstance(v.type, QAPISchemaEnumType):
  512. for m in v.type.members:
  513. if m.name in ['on', 'off']:
  514. conflicting.add('QTYPE_QBOOL')
  515. if re.match(r'[-+0-9.]', m.name):
  516. # lazy, could be tightened
  517. conflicting.add('QTYPE_QNUM')
  518. else:
  519. conflicting.add('QTYPE_QNUM')
  520. conflicting.add('QTYPE_QBOOL')
  521. for qt in conflicting:
  522. if qt in types_seen:
  523. raise QAPISemError(
  524. self.info,
  525. "%s can't be distinguished from '%s'"
  526. % (v.describe(self.info), types_seen[qt]))
  527. types_seen[qt] = v.name
  528. if self.doc:
  529. self.doc.connect_member(v)
  530. if self.doc:
  531. self.doc.check()
  532. def c_type(self):
  533. return c_name(self.name) + pointer_suffix
  534. def json_type(self):
  535. return 'value'
  536. def visit(self, visitor):
  537. QAPISchemaType.visit(self, visitor)
  538. visitor.visit_alternate_type(self.name, self.info, self.ifcond,
  539. self.variants)
  540. class QAPISchemaCommand(QAPISchemaEntity):
  541. meta = 'command'
  542. def __init__(self, name, info, doc, ifcond, arg_type, ret_type,
  543. gen, success_response, boxed, allow_oob, allow_preconfig):
  544. QAPISchemaEntity.__init__(self, name, info, doc, ifcond)
  545. assert not arg_type or isinstance(arg_type, str)
  546. assert not ret_type or isinstance(ret_type, str)
  547. self._arg_type_name = arg_type
  548. self.arg_type = None
  549. self._ret_type_name = ret_type
  550. self.ret_type = None
  551. self.gen = gen
  552. self.success_response = success_response
  553. self.boxed = boxed
  554. self.allow_oob = allow_oob
  555. self.allow_preconfig = allow_preconfig
  556. def check(self, schema):
  557. QAPISchemaEntity.check(self, schema)
  558. if self._arg_type_name:
  559. self.arg_type = schema.resolve_type(
  560. self._arg_type_name, self.info, "command's 'data'")
  561. if not isinstance(self.arg_type, QAPISchemaObjectType):
  562. raise QAPISemError(
  563. self.info,
  564. "command's 'data' cannot take %s"
  565. % self.arg_type.describe())
  566. if self.arg_type.variants and not self.boxed:
  567. raise QAPISemError(
  568. self.info,
  569. "command's 'data' can take %s only with 'boxed': true"
  570. % self.arg_type.describe())
  571. if self._ret_type_name:
  572. self.ret_type = schema.resolve_type(
  573. self._ret_type_name, self.info, "command's 'returns'")
  574. if self.name not in self.info.pragma.returns_whitelist:
  575. if not (isinstance(self.ret_type, QAPISchemaObjectType)
  576. or (isinstance(self.ret_type, QAPISchemaArrayType)
  577. and isinstance(self.ret_type.element_type,
  578. QAPISchemaObjectType))):
  579. raise QAPISemError(
  580. self.info,
  581. "command's 'returns' cannot take %s"
  582. % self.ret_type.describe())
  583. def visit(self, visitor):
  584. QAPISchemaEntity.visit(self, visitor)
  585. visitor.visit_command(self.name, self.info, self.ifcond,
  586. self.arg_type, self.ret_type,
  587. self.gen, self.success_response,
  588. self.boxed, self.allow_oob,
  589. self.allow_preconfig)
  590. class QAPISchemaEvent(QAPISchemaEntity):
  591. meta = 'event'
  592. def __init__(self, name, info, doc, ifcond, arg_type, boxed):
  593. QAPISchemaEntity.__init__(self, name, info, doc, ifcond)
  594. assert not arg_type or isinstance(arg_type, str)
  595. self._arg_type_name = arg_type
  596. self.arg_type = None
  597. self.boxed = boxed
  598. def check(self, schema):
  599. QAPISchemaEntity.check(self, schema)
  600. if self._arg_type_name:
  601. self.arg_type = schema.resolve_type(
  602. self._arg_type_name, self.info, "event's 'data'")
  603. if not isinstance(self.arg_type, QAPISchemaObjectType):
  604. raise QAPISemError(
  605. self.info,
  606. "event's 'data' cannot take %s"
  607. % self.arg_type.describe())
  608. if self.arg_type.variants and not self.boxed:
  609. raise QAPISemError(
  610. self.info,
  611. "event's 'data' can take %s only with 'boxed': true"
  612. % self.arg_type.describe())
  613. def visit(self, visitor):
  614. QAPISchemaEntity.visit(self, visitor)
  615. visitor.visit_event(self.name, self.info, self.ifcond,
  616. self.arg_type, self.boxed)
  617. class QAPISchema(object):
  618. def __init__(self, fname):
  619. self.fname = fname
  620. parser = QAPISchemaParser(fname)
  621. exprs = check_exprs(parser.exprs)
  622. self.docs = parser.docs
  623. self._entity_list = []
  624. self._entity_dict = {}
  625. self._predefining = True
  626. self._def_predefineds()
  627. self._predefining = False
  628. self._def_exprs(exprs)
  629. self.check()
  630. def _def_entity(self, ent):
  631. # Only the predefined types are allowed to not have info
  632. assert ent.info or self._predefining
  633. self._entity_list.append(ent)
  634. if ent.name is None:
  635. return
  636. # TODO reject names that differ only in '_' vs. '.' vs. '-',
  637. # because they're liable to clash in generated C.
  638. other_ent = self._entity_dict.get(ent.name)
  639. if other_ent:
  640. if other_ent.info:
  641. where = QAPIError(other_ent.info, None, "previous definition")
  642. raise QAPISemError(
  643. ent.info,
  644. "'%s' is already defined\n%s" % (ent.name, where))
  645. raise QAPISemError(
  646. ent.info, "%s is already defined" % other_ent.describe())
  647. self._entity_dict[ent.name] = ent
  648. def lookup_entity(self, name, typ=None):
  649. ent = self._entity_dict.get(name)
  650. if typ and not isinstance(ent, typ):
  651. return None
  652. return ent
  653. def lookup_type(self, name):
  654. return self.lookup_entity(name, QAPISchemaType)
  655. def resolve_type(self, name, info, what):
  656. typ = self.lookup_type(name)
  657. if not typ:
  658. if callable(what):
  659. what = what(info)
  660. raise QAPISemError(
  661. info, "%s uses unknown type '%s'" % (what, name))
  662. return typ
  663. def _def_include(self, expr, info, doc):
  664. include = expr['include']
  665. assert doc is None
  666. main_info = info
  667. while main_info.parent:
  668. main_info = main_info.parent
  669. fname = os.path.relpath(include, os.path.dirname(main_info.fname))
  670. self._def_entity(QAPISchemaInclude(fname, info))
  671. def _def_builtin_type(self, name, json_type, c_type):
  672. self._def_entity(QAPISchemaBuiltinType(name, json_type, c_type))
  673. # Instantiating only the arrays that are actually used would
  674. # be nice, but we can't as long as their generated code
  675. # (qapi-builtin-types.[ch]) may be shared by some other
  676. # schema.
  677. self._make_array_type(name, None)
  678. def _def_predefineds(self):
  679. for t in [('str', 'string', 'char' + pointer_suffix),
  680. ('number', 'number', 'double'),
  681. ('int', 'int', 'int64_t'),
  682. ('int8', 'int', 'int8_t'),
  683. ('int16', 'int', 'int16_t'),
  684. ('int32', 'int', 'int32_t'),
  685. ('int64', 'int', 'int64_t'),
  686. ('uint8', 'int', 'uint8_t'),
  687. ('uint16', 'int', 'uint16_t'),
  688. ('uint32', 'int', 'uint32_t'),
  689. ('uint64', 'int', 'uint64_t'),
  690. ('size', 'int', 'uint64_t'),
  691. ('bool', 'boolean', 'bool'),
  692. ('any', 'value', 'QObject' + pointer_suffix),
  693. ('null', 'null', 'QNull' + pointer_suffix)]:
  694. self._def_builtin_type(*t)
  695. self.the_empty_object_type = QAPISchemaObjectType(
  696. 'q_empty', None, None, None, None, [], None, [])
  697. self._def_entity(self.the_empty_object_type)
  698. qtypes = ['none', 'qnull', 'qnum', 'qstring', 'qdict', 'qlist',
  699. 'qbool']
  700. qtype_values = self._make_enum_members(
  701. [{'name': n} for n in qtypes], None)
  702. self._def_entity(QAPISchemaEnumType('QType', None, None, None,
  703. qtype_values, 'QTYPE'))
  704. def _make_features(self, features, info):
  705. return [QAPISchemaFeature(f['name'], info, f.get('if'))
  706. for f in features]
  707. def _make_enum_members(self, values, info):
  708. return [QAPISchemaEnumMember(v['name'], info, v.get('if'))
  709. for v in values]
  710. def _make_implicit_enum_type(self, name, info, ifcond, values):
  711. # See also QAPISchemaObjectTypeMember.describe()
  712. name = name + 'Kind' # reserved by check_defn_name_str()
  713. self._def_entity(QAPISchemaEnumType(
  714. name, info, None, ifcond, self._make_enum_members(values, info),
  715. None))
  716. return name
  717. def _make_array_type(self, element_type, info):
  718. name = element_type + 'List' # reserved by check_defn_name_str()
  719. if not self.lookup_type(name):
  720. self._def_entity(QAPISchemaArrayType(name, info, element_type))
  721. return name
  722. def _make_implicit_object_type(self, name, info, doc, ifcond,
  723. role, members):
  724. if not members:
  725. return None
  726. # See also QAPISchemaObjectTypeMember.describe()
  727. name = 'q_obj_%s-%s' % (name, role)
  728. typ = self.lookup_entity(name, QAPISchemaObjectType)
  729. if typ:
  730. # The implicit object type has multiple users. This can
  731. # happen only for simple unions' implicit wrapper types.
  732. # Its ifcond should be the disjunction of its user's
  733. # ifconds. Not implemented. Instead, we always pass the
  734. # wrapped type's ifcond, which is trivially the same for all
  735. # users. It's also necessary for the wrapper to compile.
  736. # But it's not tight: the disjunction need not imply it. We
  737. # may end up compiling useless wrapper types.
  738. # TODO kill simple unions or implement the disjunction
  739. assert (ifcond or []) == typ._ifcond # pylint: disable=protected-access
  740. else:
  741. self._def_entity(QAPISchemaObjectType(name, info, doc, ifcond,
  742. None, members, None, []))
  743. return name
  744. def _def_enum_type(self, expr, info, doc):
  745. name = expr['enum']
  746. data = expr['data']
  747. prefix = expr.get('prefix')
  748. ifcond = expr.get('if')
  749. self._def_entity(QAPISchemaEnumType(
  750. name, info, doc, ifcond,
  751. self._make_enum_members(data, info), prefix))
  752. def _make_member(self, name, typ, ifcond, info):
  753. optional = False
  754. if name.startswith('*'):
  755. name = name[1:]
  756. optional = True
  757. if isinstance(typ, list):
  758. assert len(typ) == 1
  759. typ = self._make_array_type(typ[0], info)
  760. return QAPISchemaObjectTypeMember(name, info, typ, optional, ifcond)
  761. def _make_members(self, data, info):
  762. return [self._make_member(key, value['type'], value.get('if'), info)
  763. for (key, value) in data.items()]
  764. def _def_struct_type(self, expr, info, doc):
  765. name = expr['struct']
  766. base = expr.get('base')
  767. data = expr['data']
  768. ifcond = expr.get('if')
  769. features = expr.get('features', [])
  770. self._def_entity(QAPISchemaObjectType(
  771. name, info, doc, ifcond, base,
  772. self._make_members(data, info),
  773. None,
  774. self._make_features(features, info)))
  775. def _make_variant(self, case, typ, ifcond, info):
  776. return QAPISchemaObjectTypeVariant(case, info, typ, ifcond)
  777. def _make_simple_variant(self, case, typ, ifcond, info):
  778. if isinstance(typ, list):
  779. assert len(typ) == 1
  780. typ = self._make_array_type(typ[0], info)
  781. typ = self._make_implicit_object_type(
  782. typ, info, None, self.lookup_type(typ),
  783. 'wrapper', [self._make_member('data', typ, None, info)])
  784. return QAPISchemaObjectTypeVariant(case, info, typ, ifcond)
  785. def _def_union_type(self, expr, info, doc):
  786. name = expr['union']
  787. data = expr['data']
  788. base = expr.get('base')
  789. ifcond = expr.get('if')
  790. tag_name = expr.get('discriminator')
  791. tag_member = None
  792. if isinstance(base, dict):
  793. base = self._make_implicit_object_type(
  794. name, info, doc, ifcond,
  795. 'base', self._make_members(base, info))
  796. if tag_name:
  797. variants = [self._make_variant(key, value['type'],
  798. value.get('if'), info)
  799. for (key, value) in data.items()]
  800. members = []
  801. else:
  802. variants = [self._make_simple_variant(key, value['type'],
  803. value.get('if'), info)
  804. for (key, value) in data.items()]
  805. enum = [{'name': v.name, 'if': v.ifcond} for v in variants]
  806. typ = self._make_implicit_enum_type(name, info, ifcond, enum)
  807. tag_member = QAPISchemaObjectTypeMember('type', info, typ, False)
  808. members = [tag_member]
  809. self._def_entity(
  810. QAPISchemaObjectType(name, info, doc, ifcond, base, members,
  811. QAPISchemaObjectTypeVariants(
  812. tag_name, info, tag_member, variants),
  813. []))
  814. def _def_alternate_type(self, expr, info, doc):
  815. name = expr['alternate']
  816. data = expr['data']
  817. ifcond = expr.get('if')
  818. variants = [self._make_variant(key, value['type'], value.get('if'),
  819. info)
  820. for (key, value) in data.items()]
  821. tag_member = QAPISchemaObjectTypeMember('type', info, 'QType', False)
  822. self._def_entity(
  823. QAPISchemaAlternateType(name, info, doc, ifcond,
  824. QAPISchemaObjectTypeVariants(
  825. None, info, tag_member, variants)))
  826. def _def_command(self, expr, info, doc):
  827. name = expr['command']
  828. data = expr.get('data')
  829. rets = expr.get('returns')
  830. gen = expr.get('gen', True)
  831. success_response = expr.get('success-response', True)
  832. boxed = expr.get('boxed', False)
  833. allow_oob = expr.get('allow-oob', False)
  834. allow_preconfig = expr.get('allow-preconfig', False)
  835. ifcond = expr.get('if')
  836. if isinstance(data, OrderedDict):
  837. data = self._make_implicit_object_type(
  838. name, info, doc, ifcond, 'arg', self._make_members(data, info))
  839. if isinstance(rets, list):
  840. assert len(rets) == 1
  841. rets = self._make_array_type(rets[0], info)
  842. self._def_entity(QAPISchemaCommand(name, info, doc, ifcond, data, rets,
  843. gen, success_response,
  844. boxed, allow_oob, allow_preconfig))
  845. def _def_event(self, expr, info, doc):
  846. name = expr['event']
  847. data = expr.get('data')
  848. boxed = expr.get('boxed', False)
  849. ifcond = expr.get('if')
  850. if isinstance(data, OrderedDict):
  851. data = self._make_implicit_object_type(
  852. name, info, doc, ifcond, 'arg', self._make_members(data, info))
  853. self._def_entity(QAPISchemaEvent(name, info, doc, ifcond, data, boxed))
  854. def _def_exprs(self, exprs):
  855. for expr_elem in exprs:
  856. expr = expr_elem['expr']
  857. info = expr_elem['info']
  858. doc = expr_elem.get('doc')
  859. if 'enum' in expr:
  860. self._def_enum_type(expr, info, doc)
  861. elif 'struct' in expr:
  862. self._def_struct_type(expr, info, doc)
  863. elif 'union' in expr:
  864. self._def_union_type(expr, info, doc)
  865. elif 'alternate' in expr:
  866. self._def_alternate_type(expr, info, doc)
  867. elif 'command' in expr:
  868. self._def_command(expr, info, doc)
  869. elif 'event' in expr:
  870. self._def_event(expr, info, doc)
  871. elif 'include' in expr:
  872. self._def_include(expr, info, doc)
  873. else:
  874. assert False
  875. def check(self):
  876. for ent in self._entity_list:
  877. ent.check(self)
  878. def visit(self, visitor):
  879. visitor.visit_begin(self)
  880. module = None
  881. visitor.visit_module(module)
  882. for entity in self._entity_list:
  883. if visitor.visit_needed(entity):
  884. if entity.module != module:
  885. module = entity.module
  886. visitor.visit_module(module)
  887. entity.visit(visitor)
  888. visitor.visit_end()