expr.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  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. Dict,
  31. Iterable,
  32. List,
  33. Optional,
  34. Union,
  35. cast,
  36. )
  37. from .common import c_name
  38. from .error import QAPISemError
  39. from .parser import QAPIExpression
  40. from .source import QAPISourceInfo
  41. # See check_name_str(), below.
  42. valid_name = re.compile(r'(__[a-z0-9.-]+_)?'
  43. r'(x-)?'
  44. r'([a-z][a-z0-9_-]*)$', re.IGNORECASE)
  45. def check_name_is_str(name: object,
  46. info: QAPISourceInfo,
  47. source: str) -> None:
  48. """
  49. Ensure that ``name`` is a ``str``.
  50. :raise QAPISemError: When ``name`` fails validation.
  51. """
  52. if not isinstance(name, str):
  53. raise QAPISemError(info, "%s requires a string name" % source)
  54. def check_name_str(name: str, info: QAPISourceInfo, source: str) -> str:
  55. """
  56. Ensure that ``name`` is a valid QAPI name.
  57. A valid name consists of ASCII letters, digits, ``-``, and ``_``,
  58. starting with a letter. It may be prefixed by a downstream prefix
  59. of the form __RFQDN_, or the experimental prefix ``x-``. If both
  60. prefixes are present, the __RFDQN_ prefix goes first.
  61. A valid name cannot start with ``q_``, which is reserved.
  62. :param name: Name to check.
  63. :param info: QAPI schema source file information.
  64. :param source: Error string describing what ``name`` belongs to.
  65. :raise QAPISemError: When ``name`` fails validation.
  66. :return: The stem of the valid name, with no prefixes.
  67. """
  68. # Reserve the entire 'q_' namespace for c_name(), and for 'q_empty'
  69. # and 'q_obj_*' implicit type names.
  70. match = valid_name.match(name)
  71. if not match or c_name(name, False).startswith('q_'):
  72. raise QAPISemError(info, "%s has an invalid name" % source)
  73. return match.group(3)
  74. def check_name_upper(name: str, info: QAPISourceInfo, source: str) -> None:
  75. """
  76. Ensure that ``name`` is a valid event name.
  77. This means it must be a valid QAPI name as checked by
  78. `check_name_str()`, but where the stem prohibits lowercase
  79. characters and ``-``.
  80. :param name: Name to check.
  81. :param info: QAPI schema source file information.
  82. :param source: Error string describing what ``name`` belongs to.
  83. :raise QAPISemError: When ``name`` fails validation.
  84. """
  85. stem = check_name_str(name, info, source)
  86. if re.search(r'[a-z-]', stem):
  87. raise QAPISemError(
  88. info, "name of %s must not use lowercase or '-'" % source)
  89. def check_name_lower(name: str, info: QAPISourceInfo, source: str,
  90. permit_upper: bool = False,
  91. permit_underscore: bool = False) -> None:
  92. """
  93. Ensure that ``name`` is a valid command or member name.
  94. This means it must be a valid QAPI name as checked by
  95. `check_name_str()`, but where the stem prohibits uppercase
  96. characters and ``_``.
  97. :param name: Name to check.
  98. :param info: QAPI schema source file information.
  99. :param source: Error string describing what ``name`` belongs to.
  100. :param permit_upper: Additionally permit uppercase.
  101. :param permit_underscore: Additionally permit ``_``.
  102. :raise QAPISemError: When ``name`` fails validation.
  103. """
  104. stem = check_name_str(name, info, source)
  105. if ((not permit_upper and re.search(r'[A-Z]', stem))
  106. or (not permit_underscore and '_' in stem)):
  107. raise QAPISemError(
  108. info, "name of %s must not use uppercase or '_'" % source)
  109. def check_name_camel(name: str, info: QAPISourceInfo, source: str) -> None:
  110. """
  111. Ensure that ``name`` is a valid user-defined type name.
  112. This means it must be a valid QAPI name as checked by
  113. `check_name_str()`, but where the stem must be in CamelCase.
  114. :param name: Name to check.
  115. :param info: QAPI schema source file information.
  116. :param source: Error string describing what ``name`` belongs to.
  117. :raise QAPISemError: When ``name`` fails validation.
  118. """
  119. stem = check_name_str(name, info, source)
  120. if not re.match(r'[A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*$', stem):
  121. raise QAPISemError(info, "name of %s must use CamelCase" % source)
  122. def check_defn_name_str(name: str, info: QAPISourceInfo, meta: str) -> None:
  123. """
  124. Ensure that ``name`` is a valid definition name.
  125. Based on the value of ``meta``, this means that:
  126. - 'event' names adhere to `check_name_upper()`.
  127. - 'command' names adhere to `check_name_lower()`.
  128. - Else, meta is a type, and must pass `check_name_camel()`.
  129. These names must not end with ``List``.
  130. :param name: Name to check.
  131. :param info: QAPI schema source file information.
  132. :param meta: Meta-type name of the QAPI expression.
  133. :raise QAPISemError: When ``name`` fails validation.
  134. """
  135. if meta == 'event':
  136. check_name_upper(name, info, meta)
  137. elif meta == 'command':
  138. check_name_lower(
  139. name, info, meta,
  140. permit_underscore=name in info.pragma.command_name_exceptions)
  141. else:
  142. check_name_camel(name, info, meta)
  143. if name.endswith('List'):
  144. raise QAPISemError(
  145. info, "%s name should not end in 'List'" % meta)
  146. def check_keys(value: Dict[str, object],
  147. info: QAPISourceInfo,
  148. source: str,
  149. required: List[str],
  150. optional: List[str]) -> None:
  151. """
  152. Ensure that a dict has a specific set of keys.
  153. :param value: The dict to check.
  154. :param info: QAPI schema source file information.
  155. :param source: Error string describing this ``value``.
  156. :param required: Keys that *must* be present.
  157. :param optional: Keys that *may* be present.
  158. :raise QAPISemError: When unknown keys are present.
  159. """
  160. def pprint(elems: Iterable[str]) -> str:
  161. return ', '.join("'" + e + "'" for e in sorted(elems))
  162. missing = set(required) - set(value)
  163. if missing:
  164. raise QAPISemError(
  165. info,
  166. "%s misses key%s %s"
  167. % (source, 's' if len(missing) > 1 else '',
  168. pprint(missing)))
  169. allowed = set(required) | set(optional)
  170. unknown = set(value) - allowed
  171. if unknown:
  172. raise QAPISemError(
  173. info,
  174. "%s has unknown key%s %s\nValid keys are %s."
  175. % (source, 's' if len(unknown) > 1 else '',
  176. pprint(unknown), pprint(allowed)))
  177. def check_flags(expr: QAPIExpression) -> None:
  178. """
  179. Ensure flag members (if present) have valid values.
  180. :param expr: The expression to validate.
  181. :raise QAPISemError:
  182. When certain flags have an invalid value, or when
  183. incompatible flags are present.
  184. """
  185. for key in ('gen', 'success-response'):
  186. if key in expr and expr[key] is not False:
  187. raise QAPISemError(
  188. expr.info, "flag '%s' may only use false value" % key)
  189. for key in ('boxed', 'allow-oob', 'allow-preconfig', 'coroutine'):
  190. if key in expr and expr[key] is not True:
  191. raise QAPISemError(
  192. expr.info, "flag '%s' may only use true value" % key)
  193. if 'allow-oob' in expr and 'coroutine' in expr:
  194. # This is not necessarily a fundamental incompatibility, but
  195. # we don't have a use case and the desired semantics isn't
  196. # obvious. The simplest solution is to forbid it until we get
  197. # a use case for it.
  198. raise QAPISemError(
  199. expr.info, "flags 'allow-oob' and 'coroutine' are incompatible")
  200. def check_if(expr: Dict[str, object],
  201. info: QAPISourceInfo, source: str) -> None:
  202. """
  203. Validate the ``if`` member of an object.
  204. The ``if`` member may be either a ``str`` or a dict.
  205. :param expr: The expression containing the ``if`` member to validate.
  206. :param info: QAPI schema source file information.
  207. :param source: Error string describing ``expr``.
  208. :raise QAPISemError:
  209. When the "if" member fails validation, or when there are no
  210. non-empty conditions.
  211. :return: None
  212. """
  213. def _check_if(cond: Union[str, object]) -> None:
  214. if isinstance(cond, str):
  215. if not re.fullmatch(r'[A-Z][A-Z0-9_]*', cond):
  216. raise QAPISemError(
  217. info,
  218. "'if' condition '%s' of %s is not a valid identifier"
  219. % (cond, source))
  220. return
  221. if not isinstance(cond, dict):
  222. raise QAPISemError(
  223. info,
  224. "'if' condition of %s must be a string or an object" % source)
  225. check_keys(cond, info, "'if' condition of %s" % source, [],
  226. ["all", "any", "not"])
  227. if len(cond) != 1:
  228. raise QAPISemError(
  229. info,
  230. "'if' condition of %s has conflicting keys" % source)
  231. if 'not' in cond:
  232. _check_if(cond['not'])
  233. elif 'all' in cond:
  234. _check_infix('all', cond['all'])
  235. else:
  236. _check_infix('any', cond['any'])
  237. def _check_infix(operator: str, operands: object) -> None:
  238. if not isinstance(operands, list):
  239. raise QAPISemError(
  240. info,
  241. "'%s' condition of %s must be an array"
  242. % (operator, source))
  243. if not operands:
  244. raise QAPISemError(
  245. info, "'if' condition [] of %s is useless" % 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_name(value: Optional[object],
  270. info: QAPISourceInfo, source: str) -> None:
  271. if value is not None and not isinstance(value, str):
  272. raise QAPISemError(info, "%s should be a type name" % source)
  273. def check_type_name_or_array(value: Optional[object],
  274. info: QAPISourceInfo, source: str) -> None:
  275. if value is None or isinstance(value, str):
  276. return
  277. if not isinstance(value, list):
  278. raise QAPISemError(info,
  279. "%s should be a type name or array" % source)
  280. if len(value) != 1 or not isinstance(value[0], str):
  281. raise QAPISemError(info,
  282. "%s: array type must contain single type name" %
  283. source)
  284. def check_type_name_or_implicit(value: Optional[object],
  285. info: QAPISourceInfo, source: str,
  286. parent_name: Optional[str]) -> None:
  287. """
  288. Normalize and validate an optional implicit struct type.
  289. Accept ``None``, ``str``, or a ``dict`` defining an implicit
  290. struct type. The latter is normalized in place.
  291. :param value: The value to check.
  292. :param info: QAPI schema source file information.
  293. :param source: Error string describing this ``value``.
  294. :param parent_name:
  295. When the value of ``parent_name`` is in pragma
  296. ``member-name-exceptions``, an implicit struct type may
  297. violate the member naming rules.
  298. :raise QAPISemError: When ``value`` fails validation.
  299. :return: None
  300. """
  301. if value is None:
  302. return
  303. if isinstance(value, str):
  304. return
  305. if not isinstance(value, dict):
  306. raise QAPISemError(info,
  307. "%s should be an object or type name" % source)
  308. permissive = parent_name in info.pragma.member_name_exceptions
  309. for (key, arg) in value.items():
  310. key_source = "%s member '%s'" % (source, key)
  311. if key.startswith('*'):
  312. key = key[1:]
  313. check_name_lower(key, info, key_source,
  314. permit_upper=permissive,
  315. permit_underscore=permissive)
  316. if c_name(key, False) == 'u' or c_name(key, False).startswith('has_'):
  317. raise QAPISemError(info, "%s uses reserved name" % key_source)
  318. check_keys(arg, info, key_source, ['type'], ['if', 'features'])
  319. check_if(arg, info, key_source)
  320. check_features(arg.get('features'), info)
  321. check_type_name_or_array(arg['type'], info, key_source)
  322. def check_features(features: Optional[object],
  323. info: QAPISourceInfo) -> None:
  324. """
  325. Normalize and validate the ``features`` member.
  326. ``features`` may be a ``list`` of either ``str`` or ``dict``.
  327. Any ``str`` element will be normalized to ``{'name': element}``.
  328. :forms:
  329. :sugared: ``List[Union[str, Feature]]``
  330. :canonical: ``List[Feature]``
  331. :param features: The features member value to validate.
  332. :param info: QAPI schema source file information.
  333. :raise QAPISemError: When ``features`` fails validation.
  334. :return: None, ``features`` is normalized in-place as needed.
  335. """
  336. if features is None:
  337. return
  338. if not isinstance(features, list):
  339. raise QAPISemError(info, "'features' must be an array")
  340. features[:] = [f if isinstance(f, dict) else {'name': f}
  341. for f in features]
  342. for feat in features:
  343. source = "'features' member"
  344. assert isinstance(feat, dict)
  345. check_keys(feat, info, source, ['name'], ['if'])
  346. check_name_is_str(feat['name'], info, source)
  347. source = "%s '%s'" % (source, feat['name'])
  348. check_name_lower(feat['name'], info, source)
  349. check_if(feat, info, source)
  350. def check_enum(expr: QAPIExpression) -> None:
  351. """
  352. Normalize and validate this expression as an ``enum`` definition.
  353. :param expr: The expression to validate.
  354. :raise QAPISemError: When ``expr`` is not a valid ``enum``.
  355. :return: None, ``expr`` is normalized in-place as needed.
  356. """
  357. name = expr['enum']
  358. members = expr['data']
  359. prefix = expr.get('prefix')
  360. info = expr.info
  361. if not isinstance(members, list):
  362. raise QAPISemError(info, "'data' must be an array")
  363. if prefix is not None and not isinstance(prefix, str):
  364. raise QAPISemError(info, "'prefix' must be a string")
  365. permissive = name in info.pragma.member_name_exceptions
  366. members[:] = [m if isinstance(m, dict) else {'name': m}
  367. for m in members]
  368. for member in members:
  369. source = "'data' member"
  370. check_keys(member, info, source, ['name'], ['if', 'features'])
  371. member_name = member['name']
  372. check_name_is_str(member_name, info, source)
  373. source = "%s '%s'" % (source, member_name)
  374. # Enum members may start with a digit
  375. if member_name[0].isdigit():
  376. member_name = 'd' + member_name # Hack: hide the digit
  377. check_name_lower(member_name, info, source,
  378. permit_upper=permissive,
  379. permit_underscore=permissive)
  380. check_if(member, info, source)
  381. check_features(member.get('features'), info)
  382. def check_struct(expr: QAPIExpression) -> None:
  383. """
  384. Normalize and validate this expression as a ``struct`` definition.
  385. :param expr: The expression to validate.
  386. :raise QAPISemError: When ``expr`` is not a valid ``struct``.
  387. :return: None, ``expr`` is normalized in-place as needed.
  388. """
  389. name = cast(str, expr['struct']) # Checked in check_exprs
  390. members = expr['data']
  391. check_type_name_or_implicit(members, expr.info, "'data'", name)
  392. check_type_name(expr.get('base'), expr.info, "'base'")
  393. def check_union(expr: QAPIExpression) -> None:
  394. """
  395. Normalize and validate this expression as a ``union`` definition.
  396. :param expr: The expression to validate.
  397. :raise QAPISemError: when ``expr`` is not a valid ``union``.
  398. :return: None, ``expr`` is normalized in-place as needed.
  399. """
  400. name = cast(str, expr['union']) # Checked in check_exprs
  401. base = expr['base']
  402. discriminator = expr['discriminator']
  403. members = expr['data']
  404. info = expr.info
  405. check_type_name_or_implicit(base, info, "'base'", name)
  406. check_name_is_str(discriminator, info, "'discriminator'")
  407. if not isinstance(members, dict):
  408. raise QAPISemError(info, "'data' must be an object")
  409. for (key, value) in members.items():
  410. source = "'data' member '%s'" % key
  411. check_keys(value, info, source, ['type'], ['if'])
  412. check_if(value, info, source)
  413. check_type_name(value['type'], info, source)
  414. def check_alternate(expr: QAPIExpression) -> None:
  415. """
  416. Normalize and validate this expression as an ``alternate`` definition.
  417. :param expr: The expression to validate.
  418. :raise QAPISemError: When ``expr`` is not a valid ``alternate``.
  419. :return: None, ``expr`` is normalized in-place as needed.
  420. """
  421. members = expr['data']
  422. info = expr.info
  423. if not members:
  424. raise QAPISemError(info, "'data' must not be empty")
  425. if not isinstance(members, dict):
  426. raise QAPISemError(info, "'data' must be an object")
  427. for (key, value) in members.items():
  428. source = "'data' member '%s'" % key
  429. check_name_lower(key, info, source)
  430. check_keys(value, info, source, ['type'], ['if'])
  431. check_if(value, info, source)
  432. check_type_name_or_array(value['type'], info, source)
  433. def check_command(expr: QAPIExpression) -> None:
  434. """
  435. Normalize and validate this expression as a ``command`` definition.
  436. :param expr: The expression to validate.
  437. :raise QAPISemError: When ``expr`` is not a valid ``command``.
  438. :return: None, ``expr`` is normalized in-place as needed.
  439. """
  440. args = expr.get('data')
  441. rets = expr.get('returns')
  442. boxed = expr.get('boxed', False)
  443. if boxed:
  444. if args is None:
  445. raise QAPISemError(expr.info, "'boxed': true requires 'data'")
  446. check_type_name(args, expr.info, "'data'")
  447. else:
  448. check_type_name_or_implicit(args, expr.info, "'data'", None)
  449. check_type_name_or_array(rets, expr.info, "'returns'")
  450. def check_event(expr: QAPIExpression) -> None:
  451. """
  452. Normalize and validate this expression as an ``event`` definition.
  453. :param expr: The expression to validate.
  454. :raise QAPISemError: When ``expr`` is not a valid ``event``.
  455. :return: None, ``expr`` is normalized in-place as needed.
  456. """
  457. args = expr.get('data')
  458. boxed = expr.get('boxed', False)
  459. if boxed:
  460. if args is None:
  461. raise QAPISemError(expr.info, "'boxed': true requires 'data'")
  462. check_type_name(args, expr.info, "'data'")
  463. else:
  464. check_type_name_or_implicit(args, expr.info, "'data'", None)
  465. def check_exprs(exprs: List[QAPIExpression]) -> List[QAPIExpression]:
  466. """
  467. Validate and normalize a list of parsed QAPI schema expressions.
  468. This function accepts a list of expressions and metadata as returned
  469. by the parser. It destructively normalizes the expressions in-place.
  470. :param exprs: The list of expressions to normalize and validate.
  471. :raise QAPISemError: When any expression fails validation.
  472. :return: The same list of expressions (now modified).
  473. """
  474. for expr in exprs:
  475. info = expr.info
  476. doc = expr.doc
  477. if 'include' in expr:
  478. continue
  479. metas = expr.keys() & {'enum', 'struct', 'union', 'alternate',
  480. 'command', 'event'}
  481. if len(metas) != 1:
  482. raise QAPISemError(
  483. info,
  484. "expression must have exactly one key"
  485. " 'enum', 'struct', 'union', 'alternate',"
  486. " 'command', 'event'")
  487. meta = metas.pop()
  488. check_name_is_str(expr[meta], info, "'%s'" % meta)
  489. name = cast(str, expr[meta])
  490. info.set_defn(meta, name)
  491. check_defn_name_str(name, info, meta)
  492. if doc:
  493. if doc.symbol != name:
  494. raise QAPISemError(
  495. info, "documentation comment is for '%s'" % doc.symbol)
  496. doc.check_expr(expr)
  497. elif info.pragma.doc_required:
  498. raise QAPISemError(info,
  499. "documentation comment required")
  500. if meta == 'enum':
  501. check_keys(expr, info, meta,
  502. ['enum', 'data'], ['if', 'features', 'prefix'])
  503. check_enum(expr)
  504. elif meta == 'union':
  505. check_keys(expr, info, meta,
  506. ['union', 'base', 'discriminator', 'data'],
  507. ['if', 'features'])
  508. normalize_members(expr.get('base'))
  509. normalize_members(expr['data'])
  510. check_union(expr)
  511. elif meta == 'alternate':
  512. check_keys(expr, info, meta,
  513. ['alternate', 'data'], ['if', 'features'])
  514. normalize_members(expr['data'])
  515. check_alternate(expr)
  516. elif meta == 'struct':
  517. check_keys(expr, info, meta,
  518. ['struct', 'data'], ['base', 'if', 'features'])
  519. normalize_members(expr['data'])
  520. check_struct(expr)
  521. elif meta == 'command':
  522. check_keys(expr, info, meta,
  523. ['command'],
  524. ['data', 'returns', 'boxed', 'if', 'features',
  525. 'gen', 'success-response', 'allow-oob',
  526. 'allow-preconfig', 'coroutine'])
  527. normalize_members(expr.get('data'))
  528. check_command(expr)
  529. elif meta == 'event':
  530. check_keys(expr, info, meta,
  531. ['event'], ['data', 'boxed', 'if', 'features'])
  532. normalize_members(expr.get('data'))
  533. check_event(expr)
  534. else:
  535. assert False, 'unexpected meta type'
  536. check_if(expr, info, meta)
  537. check_features(expr.get('features'), info)
  538. check_flags(expr)
  539. return exprs