2
0

expr.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright IBM, Corp. 2011
  4. # Copyright (c) 2013-2021 Red Hat Inc.
  5. #
  6. # Authors:
  7. # Anthony Liguori <aliguori@us.ibm.com>
  8. # Markus Armbruster <armbru@redhat.com>
  9. # Eric Blake <eblake@redhat.com>
  10. # Marc-André Lureau <marcandre.lureau@redhat.com>
  11. # John Snow <jsnow@redhat.com>
  12. #
  13. # This work is licensed under the terms of the GNU GPL, version 2.
  14. # See the COPYING file in the top-level directory.
  15. """
  16. Normalize and validate (context-free) QAPI schema expression structures.
  17. `QAPISchemaParser` parses a QAPI schema into abstract syntax trees
  18. consisting of dict, list, str, bool, and int nodes. This module ensures
  19. that these nested structures have the correct type(s) and key(s) where
  20. appropriate for the QAPI context-free grammar.
  21. The QAPI schema expression language allows for certain syntactic sugar;
  22. this module also handles the normalization process of these nested
  23. structures.
  24. See `check_exprs` for the main entry point.
  25. See `schema.QAPISchema` for processing into native Python data
  26. structures and contextual semantic validation.
  27. """
  28. import re
  29. from typing import (
  30. Collection,
  31. Dict,
  32. Iterable,
  33. List,
  34. Optional,
  35. Union,
  36. cast,
  37. )
  38. from .common import c_name
  39. from .error import QAPISemError
  40. from .parser import QAPIDoc
  41. from .source import QAPISourceInfo
  42. # Deserialized JSON objects as returned by the parser.
  43. # The values of this mapping are not necessary to exhaustively type
  44. # here (and also not practical as long as mypy lacks recursive
  45. # types), because the purpose of this module is to interrogate that
  46. # type.
  47. _JSONObject = Dict[str, object]
  48. # See check_name_str(), below.
  49. valid_name = re.compile(r'(__[a-z0-9.-]+_)?'
  50. r'(x-)?'
  51. r'([a-z][a-z0-9_-]*)$', re.IGNORECASE)
  52. def check_name_is_str(name: object,
  53. info: QAPISourceInfo,
  54. source: str) -> None:
  55. """
  56. Ensure that ``name`` is a ``str``.
  57. :raise QAPISemError: When ``name`` fails validation.
  58. """
  59. if not isinstance(name, str):
  60. raise QAPISemError(info, "%s requires a string name" % source)
  61. def check_name_str(name: str, info: QAPISourceInfo, source: str) -> str:
  62. """
  63. Ensure that ``name`` is a valid QAPI name.
  64. A valid name consists of ASCII letters, digits, ``-``, and ``_``,
  65. starting with a letter. It may be prefixed by a downstream prefix
  66. of the form __RFQDN_, or the experimental prefix ``x-``. If both
  67. prefixes are present, the __RFDQN_ prefix goes first.
  68. A valid name cannot start with ``q_``, which is reserved.
  69. :param name: Name to check.
  70. :param info: QAPI schema source file information.
  71. :param source: Error string describing what ``name`` belongs to.
  72. :raise QAPISemError: When ``name`` fails validation.
  73. :return: The stem of the valid name, with no prefixes.
  74. """
  75. # Reserve the entire 'q_' namespace for c_name(), and for 'q_empty'
  76. # and 'q_obj_*' implicit type names.
  77. match = valid_name.match(name)
  78. if not match or c_name(name, False).startswith('q_'):
  79. raise QAPISemError(info, "%s has an invalid name" % source)
  80. return match.group(3)
  81. def check_name_upper(name: str, info: QAPISourceInfo, source: str) -> None:
  82. """
  83. Ensure that ``name`` is a valid event name.
  84. This means it must be a valid QAPI name as checked by
  85. `check_name_str()`, but where the stem prohibits lowercase
  86. characters and ``-``.
  87. :param name: Name to check.
  88. :param info: QAPI schema source file information.
  89. :param source: Error string describing what ``name`` belongs to.
  90. :raise QAPISemError: When ``name`` fails validation.
  91. """
  92. stem = check_name_str(name, info, source)
  93. if re.search(r'[a-z-]', stem):
  94. raise QAPISemError(
  95. info, "name of %s must not use lowercase or '-'" % source)
  96. def check_name_lower(name: str, info: QAPISourceInfo, source: str,
  97. permit_upper: bool = False,
  98. permit_underscore: bool = False) -> None:
  99. """
  100. Ensure that ``name`` is a valid command or member name.
  101. This means it must be a valid QAPI name as checked by
  102. `check_name_str()`, but where the stem prohibits uppercase
  103. characters and ``_``.
  104. :param name: Name to check.
  105. :param info: QAPI schema source file information.
  106. :param source: Error string describing what ``name`` belongs to.
  107. :param permit_upper: Additionally permit uppercase.
  108. :param permit_underscore: Additionally permit ``_``.
  109. :raise QAPISemError: When ``name`` fails validation.
  110. """
  111. stem = check_name_str(name, info, source)
  112. if ((not permit_upper and re.search(r'[A-Z]', stem))
  113. or (not permit_underscore and '_' in stem)):
  114. raise QAPISemError(
  115. info, "name of %s must not use uppercase or '_'" % source)
  116. def check_name_camel(name: str, info: QAPISourceInfo, source: str) -> None:
  117. """
  118. Ensure that ``name`` is a valid user-defined type name.
  119. This means it must be a valid QAPI name as checked by
  120. `check_name_str()`, but where the stem must be in CamelCase.
  121. :param name: Name to check.
  122. :param info: QAPI schema source file information.
  123. :param source: Error string describing what ``name`` belongs to.
  124. :raise QAPISemError: When ``name`` fails validation.
  125. """
  126. stem = check_name_str(name, info, source)
  127. if not re.match(r'[A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*$', stem):
  128. raise QAPISemError(info, "name of %s must use CamelCase" % source)
  129. def check_defn_name_str(name: str, info: QAPISourceInfo, meta: str) -> None:
  130. """
  131. Ensure that ``name`` is a valid definition name.
  132. Based on the value of ``meta``, this means that:
  133. - 'event' names adhere to `check_name_upper()`.
  134. - 'command' names adhere to `check_name_lower()`.
  135. - Else, meta is a type, and must pass `check_name_camel()`.
  136. These names must not end with ``Kind`` nor ``List``.
  137. :param name: Name to check.
  138. :param info: QAPI schema source file information.
  139. :param meta: Meta-type name of the QAPI expression.
  140. :raise QAPISemError: When ``name`` fails validation.
  141. """
  142. if meta == 'event':
  143. check_name_upper(name, info, meta)
  144. elif meta == 'command':
  145. check_name_lower(
  146. name, info, meta,
  147. permit_underscore=name in info.pragma.command_name_exceptions)
  148. else:
  149. check_name_camel(name, info, meta)
  150. if name.endswith('Kind') or name.endswith('List'):
  151. raise QAPISemError(
  152. info, "%s name should not end in '%s'" % (meta, name[-4:]))
  153. def check_keys(value: _JSONObject,
  154. info: QAPISourceInfo,
  155. source: str,
  156. required: Collection[str],
  157. optional: Collection[str]) -> None:
  158. """
  159. Ensure that a dict has a specific set of keys.
  160. :param value: The dict to check.
  161. :param info: QAPI schema source file information.
  162. :param source: Error string describing this ``value``.
  163. :param required: Keys that *must* be present.
  164. :param optional: Keys that *may* be present.
  165. :raise QAPISemError: When unknown keys are present.
  166. """
  167. def pprint(elems: Iterable[str]) -> str:
  168. return ', '.join("'" + e + "'" for e in sorted(elems))
  169. missing = set(required) - set(value)
  170. if missing:
  171. raise QAPISemError(
  172. info,
  173. "%s misses key%s %s"
  174. % (source, 's' if len(missing) > 1 else '',
  175. pprint(missing)))
  176. allowed = set(required) | set(optional)
  177. unknown = set(value) - allowed
  178. if unknown:
  179. raise QAPISemError(
  180. info,
  181. "%s has unknown key%s %s\nValid keys are %s."
  182. % (source, 's' if len(unknown) > 1 else '',
  183. pprint(unknown), pprint(allowed)))
  184. def check_flags(expr: _JSONObject, info: QAPISourceInfo) -> None:
  185. """
  186. Ensure flag members (if present) have valid values.
  187. :param expr: The expression to validate.
  188. :param info: QAPI schema source file information.
  189. :raise QAPISemError:
  190. When certain flags have an invalid value, or when
  191. incompatible flags are present.
  192. """
  193. for key in ('gen', 'success-response'):
  194. if key in expr and expr[key] is not False:
  195. raise QAPISemError(
  196. info, "flag '%s' may only use false value" % key)
  197. for key in ('boxed', 'allow-oob', 'allow-preconfig', 'coroutine'):
  198. if key in expr and expr[key] is not True:
  199. raise QAPISemError(
  200. info, "flag '%s' may only use true value" % key)
  201. if 'allow-oob' in expr and 'coroutine' in expr:
  202. # This is not necessarily a fundamental incompatibility, but
  203. # we don't have a use case and the desired semantics isn't
  204. # obvious. The simplest solution is to forbid it until we get
  205. # a use case for it.
  206. raise QAPISemError(info, "flags 'allow-oob' and 'coroutine' "
  207. "are incompatible")
  208. def check_if(expr: _JSONObject, info: QAPISourceInfo, source: str) -> None:
  209. """
  210. Validate the ``if`` member of an object.
  211. The ``if`` member may be either a ``str`` or a dict.
  212. :param expr: The expression containing the ``if`` member to validate.
  213. :param info: QAPI schema source file information.
  214. :param source: Error string describing ``expr``.
  215. :raise QAPISemError:
  216. When the "if" member fails validation, or when there are no
  217. non-empty conditions.
  218. :return: None
  219. """
  220. def _check_if(cond: Union[str, object]) -> None:
  221. if isinstance(cond, str):
  222. if not cond.strip():
  223. raise QAPISemError(
  224. info,
  225. "'if' condition '%s' of %s makes no sense"
  226. % (cond, source))
  227. return
  228. if not isinstance(cond, dict):
  229. raise QAPISemError(
  230. info,
  231. "'if' condition of %s must be a string or an object" % source)
  232. if len(cond) != 1:
  233. raise QAPISemError(
  234. info,
  235. "'if' condition dict of %s must have one key: "
  236. "'all'" % source)
  237. check_keys(cond, info, "'if' condition", [],
  238. ["all"])
  239. oper, operands = next(iter(cond.items()))
  240. if not operands:
  241. raise QAPISemError(
  242. info, "'if' condition [] of %s is useless" % source)
  243. if oper in ("all") and not isinstance(operands, list):
  244. raise QAPISemError(
  245. info, "'%s' condition of %s must be an array" % (oper, source))
  246. for operand in operands:
  247. _check_if(operand)
  248. ifcond = expr.get('if')
  249. if ifcond is None:
  250. return
  251. _check_if(ifcond)
  252. def normalize_members(members: object) -> None:
  253. """
  254. Normalize a "members" value.
  255. If ``members`` is a dict, for every value in that dict, if that
  256. value is not itself already a dict, normalize it to
  257. ``{'type': value}``.
  258. :forms:
  259. :sugared: ``Dict[str, Union[str, TypeRef]]``
  260. :canonical: ``Dict[str, TypeRef]``
  261. :param members: The members value to normalize.
  262. :return: None, ``members`` is normalized in-place as needed.
  263. """
  264. if isinstance(members, dict):
  265. for key, arg in members.items():
  266. if isinstance(arg, dict):
  267. continue
  268. members[key] = {'type': arg}
  269. def check_type(value: Optional[object],
  270. info: QAPISourceInfo,
  271. source: str,
  272. allow_array: bool = False,
  273. allow_dict: Union[bool, str] = False) -> None:
  274. """
  275. Normalize and validate the QAPI type of ``value``.
  276. Python types of ``str`` or ``None`` are always allowed.
  277. :param value: The value to check.
  278. :param info: QAPI schema source file information.
  279. :param source: Error string describing this ``value``.
  280. :param allow_array:
  281. Allow a ``List[str]`` of length 1, which indicates an array of
  282. the type named by the list element.
  283. :param allow_dict:
  284. Allow a dict. Its members can be struct type members or union
  285. branches. When the value of ``allow_dict`` is in pragma
  286. ``member-name-exceptions``, the dict's keys may violate the
  287. member naming rules. The dict members are normalized in place.
  288. :raise QAPISemError: When ``value`` fails validation.
  289. :return: None, ``value`` is normalized in-place as needed.
  290. """
  291. if value is None:
  292. return
  293. # Type name
  294. if isinstance(value, str):
  295. return
  296. # Array type
  297. if isinstance(value, list):
  298. if not allow_array:
  299. raise QAPISemError(info, "%s cannot be an array" % source)
  300. if len(value) != 1 or not isinstance(value[0], str):
  301. raise QAPISemError(info,
  302. "%s: array type must contain single type name" %
  303. source)
  304. return
  305. # Anonymous type
  306. if not allow_dict:
  307. raise QAPISemError(info, "%s should be a type name" % source)
  308. if not isinstance(value, dict):
  309. raise QAPISemError(info,
  310. "%s should be an object or type name" % source)
  311. permissive = False
  312. if isinstance(allow_dict, str):
  313. permissive = allow_dict in info.pragma.member_name_exceptions
  314. # value is a dictionary, check that each member is okay
  315. for (key, arg) in value.items():
  316. key_source = "%s member '%s'" % (source, key)
  317. if key.startswith('*'):
  318. key = key[1:]
  319. check_name_lower(key, info, key_source,
  320. permit_upper=permissive,
  321. permit_underscore=permissive)
  322. if c_name(key, False) == 'u' or c_name(key, False).startswith('has_'):
  323. raise QAPISemError(info, "%s uses reserved name" % key_source)
  324. check_keys(arg, info, key_source, ['type'], ['if', 'features'])
  325. check_if(arg, info, key_source)
  326. check_features(arg.get('features'), info)
  327. check_type(arg['type'], info, key_source, allow_array=True)
  328. def check_features(features: Optional[object],
  329. info: QAPISourceInfo) -> None:
  330. """
  331. Normalize and validate the ``features`` member.
  332. ``features`` may be a ``list`` of either ``str`` or ``dict``.
  333. Any ``str`` element will be normalized to ``{'name': element}``.
  334. :forms:
  335. :sugared: ``List[Union[str, Feature]]``
  336. :canonical: ``List[Feature]``
  337. :param features: The features member value to validate.
  338. :param info: QAPI schema source file information.
  339. :raise QAPISemError: When ``features`` fails validation.
  340. :return: None, ``features`` is normalized in-place as needed.
  341. """
  342. if features is None:
  343. return
  344. if not isinstance(features, list):
  345. raise QAPISemError(info, "'features' must be an array")
  346. features[:] = [f if isinstance(f, dict) else {'name': f}
  347. for f in features]
  348. for feat in features:
  349. source = "'features' member"
  350. assert isinstance(feat, dict)
  351. check_keys(feat, info, source, ['name'], ['if'])
  352. check_name_is_str(feat['name'], info, source)
  353. source = "%s '%s'" % (source, feat['name'])
  354. check_name_str(feat['name'], info, source)
  355. check_if(feat, info, source)
  356. def check_enum(expr: _JSONObject, info: QAPISourceInfo) -> None:
  357. """
  358. Normalize and validate this expression as an ``enum`` definition.
  359. :param expr: The expression to validate.
  360. :param info: QAPI schema source file information.
  361. :raise QAPISemError: When ``expr`` is not a valid ``enum``.
  362. :return: None, ``expr`` is normalized in-place as needed.
  363. """
  364. name = expr['enum']
  365. members = expr['data']
  366. prefix = expr.get('prefix')
  367. if not isinstance(members, list):
  368. raise QAPISemError(info, "'data' must be an array")
  369. if prefix is not None and not isinstance(prefix, str):
  370. raise QAPISemError(info, "'prefix' must be a string")
  371. permissive = name in info.pragma.member_name_exceptions
  372. members[:] = [m if isinstance(m, dict) else {'name': m}
  373. for m in members]
  374. for member in members:
  375. source = "'data' member"
  376. check_keys(member, info, source, ['name'], ['if'])
  377. member_name = member['name']
  378. check_name_is_str(member_name, info, source)
  379. source = "%s '%s'" % (source, member_name)
  380. # Enum members may start with a digit
  381. if member_name[0].isdigit():
  382. member_name = 'd' + member_name # Hack: hide the digit
  383. check_name_lower(member_name, info, source,
  384. permit_upper=permissive,
  385. permit_underscore=permissive)
  386. check_if(member, info, source)
  387. def check_struct(expr: _JSONObject, info: QAPISourceInfo) -> None:
  388. """
  389. Normalize and validate this expression as a ``struct`` definition.
  390. :param expr: The expression to validate.
  391. :param info: QAPI schema source file information.
  392. :raise QAPISemError: When ``expr`` is not a valid ``struct``.
  393. :return: None, ``expr`` is normalized in-place as needed.
  394. """
  395. name = cast(str, expr['struct']) # Checked in check_exprs
  396. members = expr['data']
  397. check_type(members, info, "'data'", allow_dict=name)
  398. check_type(expr.get('base'), info, "'base'")
  399. def check_union(expr: _JSONObject, info: QAPISourceInfo) -> None:
  400. """
  401. Normalize and validate this expression as a ``union`` definition.
  402. :param expr: The expression to validate.
  403. :param info: QAPI schema source file information.
  404. :raise QAPISemError: when ``expr`` is not a valid ``union``.
  405. :return: None, ``expr`` is normalized in-place as needed.
  406. """
  407. name = cast(str, expr['union']) # Checked in check_exprs
  408. base = expr.get('base')
  409. discriminator = expr.get('discriminator')
  410. members = expr['data']
  411. if discriminator is None: # simple union
  412. if base is not None:
  413. raise QAPISemError(info, "'base' requires 'discriminator'")
  414. else: # flat union
  415. check_type(base, info, "'base'", allow_dict=name)
  416. if not base:
  417. raise QAPISemError(info, "'discriminator' requires 'base'")
  418. check_name_is_str(discriminator, info, "'discriminator'")
  419. if not isinstance(members, dict):
  420. raise QAPISemError(info, "'data' must be an object")
  421. for (key, value) in members.items():
  422. source = "'data' member '%s'" % key
  423. if discriminator is None:
  424. check_name_lower(key, info, source)
  425. # else: name is in discriminator enum, which gets checked
  426. check_keys(value, info, source, ['type'], ['if'])
  427. check_if(value, info, source)
  428. check_type(value['type'], info, source, allow_array=not base)
  429. def check_alternate(expr: _JSONObject, info: QAPISourceInfo) -> None:
  430. """
  431. Normalize and validate this expression as an ``alternate`` definition.
  432. :param expr: The expression to validate.
  433. :param info: QAPI schema source file information.
  434. :raise QAPISemError: When ``expr`` is not a valid ``alternate``.
  435. :return: None, ``expr`` is normalized in-place as needed.
  436. """
  437. members = expr['data']
  438. if not members:
  439. raise QAPISemError(info, "'data' must not be empty")
  440. if not isinstance(members, dict):
  441. raise QAPISemError(info, "'data' must be an object")
  442. for (key, value) in members.items():
  443. source = "'data' member '%s'" % key
  444. check_name_lower(key, info, source)
  445. check_keys(value, info, source, ['type'], ['if'])
  446. check_if(value, info, source)
  447. check_type(value['type'], info, source)
  448. def check_command(expr: _JSONObject, info: QAPISourceInfo) -> None:
  449. """
  450. Normalize and validate this expression as a ``command`` definition.
  451. :param expr: The expression to validate.
  452. :param info: QAPI schema source file information.
  453. :raise QAPISemError: When ``expr`` is not a valid ``command``.
  454. :return: None, ``expr`` is normalized in-place as needed.
  455. """
  456. args = expr.get('data')
  457. rets = expr.get('returns')
  458. boxed = expr.get('boxed', False)
  459. if boxed and args is None:
  460. raise QAPISemError(info, "'boxed': true requires 'data'")
  461. check_type(args, info, "'data'", allow_dict=not boxed)
  462. check_type(rets, info, "'returns'", allow_array=True)
  463. def check_event(expr: _JSONObject, info: QAPISourceInfo) -> None:
  464. """
  465. Normalize and validate this expression as an ``event`` definition.
  466. :param expr: The expression to validate.
  467. :param info: QAPI schema source file information.
  468. :raise QAPISemError: When ``expr`` is not a valid ``event``.
  469. :return: None, ``expr`` is normalized in-place as needed.
  470. """
  471. args = expr.get('data')
  472. boxed = expr.get('boxed', False)
  473. if boxed and args is None:
  474. raise QAPISemError(info, "'boxed': true requires 'data'")
  475. check_type(args, info, "'data'", allow_dict=not boxed)
  476. def check_exprs(exprs: List[_JSONObject]) -> List[_JSONObject]:
  477. """
  478. Validate and normalize a list of parsed QAPI schema expressions.
  479. This function accepts a list of expressions and metadata as returned
  480. by the parser. It destructively normalizes the expressions in-place.
  481. :param exprs: The list of expressions to normalize and validate.
  482. :raise QAPISemError: When any expression fails validation.
  483. :return: The same list of expressions (now modified).
  484. """
  485. for expr_elem in exprs:
  486. # Expression
  487. assert isinstance(expr_elem['expr'], dict)
  488. for key in expr_elem['expr'].keys():
  489. assert isinstance(key, str)
  490. expr: _JSONObject = expr_elem['expr']
  491. # QAPISourceInfo
  492. assert isinstance(expr_elem['info'], QAPISourceInfo)
  493. info: QAPISourceInfo = expr_elem['info']
  494. # Optional[QAPIDoc]
  495. tmp = expr_elem.get('doc')
  496. assert tmp is None or isinstance(tmp, QAPIDoc)
  497. doc: Optional[QAPIDoc] = tmp
  498. if 'include' in expr:
  499. continue
  500. if 'enum' in expr:
  501. meta = 'enum'
  502. elif 'union' in expr:
  503. meta = 'union'
  504. elif 'alternate' in expr:
  505. meta = 'alternate'
  506. elif 'struct' in expr:
  507. meta = 'struct'
  508. elif 'command' in expr:
  509. meta = 'command'
  510. elif 'event' in expr:
  511. meta = 'event'
  512. else:
  513. raise QAPISemError(info, "expression is missing metatype")
  514. check_name_is_str(expr[meta], info, "'%s'" % meta)
  515. name = cast(str, expr[meta])
  516. info.set_defn(meta, name)
  517. check_defn_name_str(name, info, meta)
  518. if doc:
  519. if doc.symbol != name:
  520. raise QAPISemError(
  521. info, "documentation comment is for '%s'" % doc.symbol)
  522. doc.check_expr(expr)
  523. elif info.pragma.doc_required:
  524. raise QAPISemError(info,
  525. "documentation comment required")
  526. if meta == 'enum':
  527. check_keys(expr, info, meta,
  528. ['enum', 'data'], ['if', 'features', 'prefix'])
  529. check_enum(expr, info)
  530. elif meta == 'union':
  531. check_keys(expr, info, meta,
  532. ['union', 'data'],
  533. ['base', 'discriminator', 'if', 'features'])
  534. normalize_members(expr.get('base'))
  535. normalize_members(expr['data'])
  536. check_union(expr, info)
  537. elif meta == 'alternate':
  538. check_keys(expr, info, meta,
  539. ['alternate', 'data'], ['if', 'features'])
  540. normalize_members(expr['data'])
  541. check_alternate(expr, info)
  542. elif meta == 'struct':
  543. check_keys(expr, info, meta,
  544. ['struct', 'data'], ['base', 'if', 'features'])
  545. normalize_members(expr['data'])
  546. check_struct(expr, info)
  547. elif meta == 'command':
  548. check_keys(expr, info, meta,
  549. ['command'],
  550. ['data', 'returns', 'boxed', 'if', 'features',
  551. 'gen', 'success-response', 'allow-oob',
  552. 'allow-preconfig', 'coroutine'])
  553. normalize_members(expr.get('data'))
  554. check_command(expr, info)
  555. elif meta == 'event':
  556. check_keys(expr, info, meta,
  557. ['event'], ['data', 'boxed', 'if', 'features'])
  558. normalize_members(expr.get('data'))
  559. check_event(expr, info)
  560. else:
  561. assert False, 'unexpected meta type'
  562. check_if(expr, info, meta)
  563. check_features(expr.get('features'), info)
  564. check_flags(expr, info)
  565. return exprs