2
0

schema.py 40 KB

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