expr.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Check (context-free) QAPI schema expression structure
  4. #
  5. # Copyright IBM, Corp. 2011
  6. # Copyright (c) 2013-2019 Red Hat Inc.
  7. #
  8. # Authors:
  9. # Anthony Liguori <aliguori@us.ibm.com>
  10. # Markus Armbruster <armbru@redhat.com>
  11. # Eric Blake <eblake@redhat.com>
  12. # Marc-André Lureau <marcandre.lureau@redhat.com>
  13. #
  14. # This work is licensed under the terms of the GNU GPL, version 2.
  15. # See the COPYING file in the top-level directory.
  16. import re
  17. from typing import (
  18. Collection,
  19. Dict,
  20. Iterable,
  21. List,
  22. Optional,
  23. Union,
  24. cast,
  25. )
  26. from .common import c_name
  27. from .error import QAPISemError
  28. from .parser import QAPIDoc
  29. from .source import QAPISourceInfo
  30. # Deserialized JSON objects as returned by the parser.
  31. # The values of this mapping are not necessary to exhaustively type
  32. # here (and also not practical as long as mypy lacks recursive
  33. # types), because the purpose of this module is to interrogate that
  34. # type.
  35. _JSONObject = Dict[str, object]
  36. # Names consist of letters, digits, -, and _, starting with a letter.
  37. # An experimental name is prefixed with x-. A name of a downstream
  38. # extension is prefixed with __RFQDN_. The latter prefix goes first.
  39. valid_name = re.compile(r'(__[a-z0-9.-]+_)?'
  40. r'(x-)?'
  41. r'([a-z][a-z0-9_-]*)$', re.IGNORECASE)
  42. def check_name_is_str(name: object,
  43. info: QAPISourceInfo,
  44. source: str) -> None:
  45. if not isinstance(name, str):
  46. raise QAPISemError(info, "%s requires a string name" % source)
  47. def check_name_str(name: str, info: QAPISourceInfo, source: str) -> str:
  48. # Reserve the entire 'q_' namespace for c_name(), and for 'q_empty'
  49. # and 'q_obj_*' implicit type names.
  50. match = valid_name.match(name)
  51. if not match or c_name(name, False).startswith('q_'):
  52. raise QAPISemError(info, "%s has an invalid name" % source)
  53. return match.group(3)
  54. def check_name_upper(name: str, info: QAPISourceInfo, source: str) -> None:
  55. stem = check_name_str(name, info, source)
  56. if re.search(r'[a-z-]', stem):
  57. raise QAPISemError(
  58. info, "name of %s must not use lowercase or '-'" % source)
  59. def check_name_lower(name: str, info: QAPISourceInfo, source: str,
  60. permit_upper: bool = False,
  61. permit_underscore: bool = False) -> None:
  62. stem = check_name_str(name, info, source)
  63. if ((not permit_upper and re.search(r'[A-Z]', stem))
  64. or (not permit_underscore and '_' in stem)):
  65. raise QAPISemError(
  66. info, "name of %s must not use uppercase or '_'" % source)
  67. def check_name_camel(name: str, info: QAPISourceInfo, source: str) -> None:
  68. stem = check_name_str(name, info, source)
  69. if not re.match(r'[A-Z][A-Za-z0-9]*[a-z][A-Za-z0-9]*$', stem):
  70. raise QAPISemError(info, "name of %s must use CamelCase" % source)
  71. def check_defn_name_str(name: str, info: QAPISourceInfo, meta: str) -> None:
  72. if meta == 'event':
  73. check_name_upper(name, info, meta)
  74. elif meta == 'command':
  75. check_name_lower(
  76. name, info, meta,
  77. permit_underscore=name in info.pragma.command_name_exceptions)
  78. else:
  79. check_name_camel(name, info, meta)
  80. if name.endswith('Kind') or name.endswith('List'):
  81. raise QAPISemError(
  82. info, "%s name should not end in '%s'" % (meta, name[-4:]))
  83. def check_keys(value: _JSONObject,
  84. info: QAPISourceInfo,
  85. source: str,
  86. required: Collection[str],
  87. optional: Collection[str]) -> None:
  88. def pprint(elems: Iterable[str]) -> str:
  89. return ', '.join("'" + e + "'" for e in sorted(elems))
  90. missing = set(required) - set(value)
  91. if missing:
  92. raise QAPISemError(
  93. info,
  94. "%s misses key%s %s"
  95. % (source, 's' if len(missing) > 1 else '',
  96. pprint(missing)))
  97. allowed = set(required) | set(optional)
  98. unknown = set(value) - allowed
  99. if unknown:
  100. raise QAPISemError(
  101. info,
  102. "%s has unknown key%s %s\nValid keys are %s."
  103. % (source, 's' if len(unknown) > 1 else '',
  104. pprint(unknown), pprint(allowed)))
  105. def check_flags(expr: _JSONObject, info: QAPISourceInfo) -> None:
  106. for key in ['gen', 'success-response']:
  107. if key in expr and expr[key] is not False:
  108. raise QAPISemError(
  109. info, "flag '%s' may only use false value" % key)
  110. for key in ['boxed', 'allow-oob', 'allow-preconfig', 'coroutine']:
  111. if key in expr and expr[key] is not True:
  112. raise QAPISemError(
  113. info, "flag '%s' may only use true value" % key)
  114. if 'allow-oob' in expr and 'coroutine' in expr:
  115. # This is not necessarily a fundamental incompatibility, but
  116. # we don't have a use case and the desired semantics isn't
  117. # obvious. The simplest solution is to forbid it until we get
  118. # a use case for it.
  119. raise QAPISemError(info, "flags 'allow-oob' and 'coroutine' "
  120. "are incompatible")
  121. def check_if(expr: _JSONObject, info: QAPISourceInfo, source: str) -> None:
  122. ifcond = expr.get('if')
  123. if ifcond is None:
  124. return
  125. if isinstance(ifcond, list):
  126. if not ifcond:
  127. raise QAPISemError(
  128. info, "'if' condition [] of %s is useless" % source)
  129. else:
  130. # Normalize to a list
  131. ifcond = expr['if'] = [ifcond]
  132. for elt in ifcond:
  133. if not isinstance(elt, str):
  134. raise QAPISemError(
  135. info,
  136. "'if' condition of %s must be a string or a list of strings"
  137. % source)
  138. if not elt.strip():
  139. raise QAPISemError(
  140. info,
  141. "'if' condition '%s' of %s makes no sense"
  142. % (elt, source))
  143. def normalize_members(members: object) -> None:
  144. if isinstance(members, dict):
  145. for key, arg in members.items():
  146. if isinstance(arg, dict):
  147. continue
  148. members[key] = {'type': arg}
  149. def check_type(value: Optional[object],
  150. info: QAPISourceInfo,
  151. source: str,
  152. allow_array: bool = False,
  153. allow_dict: Union[bool, str] = False) -> None:
  154. if value is None:
  155. return
  156. # Type name
  157. if isinstance(value, str):
  158. return
  159. # Array type
  160. if isinstance(value, list):
  161. if not allow_array:
  162. raise QAPISemError(info, "%s cannot be an array" % source)
  163. if len(value) != 1 or not isinstance(value[0], str):
  164. raise QAPISemError(info,
  165. "%s: array type must contain single type name" %
  166. source)
  167. return
  168. # Anonymous type
  169. if not allow_dict:
  170. raise QAPISemError(info, "%s should be a type name" % source)
  171. if not isinstance(value, dict):
  172. raise QAPISemError(info,
  173. "%s should be an object or type name" % source)
  174. permissive = False
  175. if isinstance(allow_dict, str):
  176. permissive = allow_dict in info.pragma.member_name_exceptions
  177. # value is a dictionary, check that each member is okay
  178. for (key, arg) in value.items():
  179. key_source = "%s member '%s'" % (source, key)
  180. if key.startswith('*'):
  181. key = key[1:]
  182. check_name_lower(key, info, key_source,
  183. permit_upper=permissive,
  184. permit_underscore=permissive)
  185. if c_name(key, False) == 'u' or c_name(key, False).startswith('has_'):
  186. raise QAPISemError(info, "%s uses reserved name" % key_source)
  187. check_keys(arg, info, key_source, ['type'], ['if', 'features'])
  188. check_if(arg, info, key_source)
  189. check_features(arg.get('features'), info)
  190. check_type(arg['type'], info, key_source, allow_array=True)
  191. def check_features(features: Optional[object],
  192. info: QAPISourceInfo) -> None:
  193. if features is None:
  194. return
  195. if not isinstance(features, list):
  196. raise QAPISemError(info, "'features' must be an array")
  197. features[:] = [f if isinstance(f, dict) else {'name': f}
  198. for f in features]
  199. for feat in features:
  200. source = "'features' member"
  201. assert isinstance(feat, dict)
  202. check_keys(feat, info, source, ['name'], ['if'])
  203. check_name_is_str(feat['name'], info, source)
  204. source = "%s '%s'" % (source, feat['name'])
  205. check_name_str(feat['name'], info, source)
  206. check_if(feat, info, source)
  207. def check_enum(expr: _JSONObject, info: QAPISourceInfo) -> None:
  208. name = expr['enum']
  209. members = expr['data']
  210. prefix = expr.get('prefix')
  211. if not isinstance(members, list):
  212. raise QAPISemError(info, "'data' must be an array")
  213. if prefix is not None and not isinstance(prefix, str):
  214. raise QAPISemError(info, "'prefix' must be a string")
  215. permissive = name in info.pragma.member_name_exceptions
  216. members[:] = [m if isinstance(m, dict) else {'name': m}
  217. for m in members]
  218. for member in members:
  219. source = "'data' member"
  220. member_name = member['name']
  221. check_keys(member, info, source, ['name'], ['if'])
  222. check_name_is_str(member_name, info, source)
  223. source = "%s '%s'" % (source, member_name)
  224. # Enum members may start with a digit
  225. if member_name[0].isdigit():
  226. member_name = 'd' + member_name # Hack: hide the digit
  227. check_name_lower(member_name, info, source,
  228. permit_upper=permissive,
  229. permit_underscore=permissive)
  230. check_if(member, info, source)
  231. def check_struct(expr: _JSONObject, info: QAPISourceInfo) -> None:
  232. name = cast(str, expr['struct']) # Checked in check_exprs
  233. members = expr['data']
  234. check_type(members, info, "'data'", allow_dict=name)
  235. check_type(expr.get('base'), info, "'base'")
  236. def check_union(expr: _JSONObject, info: QAPISourceInfo) -> None:
  237. name = cast(str, expr['union']) # Checked in check_exprs
  238. base = expr.get('base')
  239. discriminator = expr.get('discriminator')
  240. members = expr['data']
  241. if discriminator is None: # simple union
  242. if base is not None:
  243. raise QAPISemError(info, "'base' requires 'discriminator'")
  244. else: # flat union
  245. check_type(base, info, "'base'", allow_dict=name)
  246. if not base:
  247. raise QAPISemError(info, "'discriminator' requires 'base'")
  248. check_name_is_str(discriminator, info, "'discriminator'")
  249. if not isinstance(members, dict):
  250. raise QAPISemError(info, "'data' must be an object")
  251. for (key, value) in members.items():
  252. source = "'data' member '%s'" % key
  253. if discriminator is None:
  254. check_name_lower(key, info, source)
  255. # else: name is in discriminator enum, which gets checked
  256. check_keys(value, info, source, ['type'], ['if'])
  257. check_if(value, info, source)
  258. check_type(value['type'], info, source, allow_array=not base)
  259. def check_alternate(expr: _JSONObject, info: QAPISourceInfo) -> None:
  260. members = expr['data']
  261. if not members:
  262. raise QAPISemError(info, "'data' must not be empty")
  263. if not isinstance(members, dict):
  264. raise QAPISemError(info, "'data' must be an object")
  265. for (key, value) in members.items():
  266. source = "'data' member '%s'" % key
  267. check_name_lower(key, info, source)
  268. check_keys(value, info, source, ['type'], ['if'])
  269. check_if(value, info, source)
  270. check_type(value['type'], info, source)
  271. def check_command(expr: _JSONObject, info: QAPISourceInfo) -> None:
  272. args = expr.get('data')
  273. rets = expr.get('returns')
  274. boxed = expr.get('boxed', False)
  275. if boxed and args is None:
  276. raise QAPISemError(info, "'boxed': true requires 'data'")
  277. check_type(args, info, "'data'", allow_dict=not boxed)
  278. check_type(rets, info, "'returns'", allow_array=True)
  279. def check_event(expr: _JSONObject, info: QAPISourceInfo) -> None:
  280. args = expr.get('data')
  281. boxed = expr.get('boxed', False)
  282. if boxed and args is None:
  283. raise QAPISemError(info, "'boxed': true requires 'data'")
  284. check_type(args, info, "'data'", allow_dict=not boxed)
  285. def check_exprs(exprs: List[_JSONObject]) -> List[_JSONObject]:
  286. for expr_elem in exprs:
  287. # Expression
  288. assert isinstance(expr_elem['expr'], dict)
  289. for key in expr_elem['expr'].keys():
  290. assert isinstance(key, str)
  291. expr: _JSONObject = expr_elem['expr']
  292. # QAPISourceInfo
  293. assert isinstance(expr_elem['info'], QAPISourceInfo)
  294. info: QAPISourceInfo = expr_elem['info']
  295. # Optional[QAPIDoc]
  296. tmp = expr_elem.get('doc')
  297. assert tmp is None or isinstance(tmp, QAPIDoc)
  298. doc: Optional[QAPIDoc] = tmp
  299. if 'include' in expr:
  300. continue
  301. if 'enum' in expr:
  302. meta = 'enum'
  303. elif 'union' in expr:
  304. meta = 'union'
  305. elif 'alternate' in expr:
  306. meta = 'alternate'
  307. elif 'struct' in expr:
  308. meta = 'struct'
  309. elif 'command' in expr:
  310. meta = 'command'
  311. elif 'event' in expr:
  312. meta = 'event'
  313. else:
  314. raise QAPISemError(info, "expression is missing metatype")
  315. check_name_is_str(expr[meta], info, "'%s'" % meta)
  316. name = cast(str, expr[meta])
  317. info.set_defn(meta, name)
  318. check_defn_name_str(name, info, meta)
  319. if doc:
  320. if doc.symbol != name:
  321. raise QAPISemError(
  322. info, "documentation comment is for '%s'" % doc.symbol)
  323. doc.check_expr(expr)
  324. elif info.pragma.doc_required:
  325. raise QAPISemError(info,
  326. "documentation comment required")
  327. if meta == 'enum':
  328. check_keys(expr, info, meta,
  329. ['enum', 'data'], ['if', 'features', 'prefix'])
  330. check_enum(expr, info)
  331. elif meta == 'union':
  332. check_keys(expr, info, meta,
  333. ['union', 'data'],
  334. ['base', 'discriminator', 'if', 'features'])
  335. normalize_members(expr.get('base'))
  336. normalize_members(expr['data'])
  337. check_union(expr, info)
  338. elif meta == 'alternate':
  339. check_keys(expr, info, meta,
  340. ['alternate', 'data'], ['if', 'features'])
  341. normalize_members(expr['data'])
  342. check_alternate(expr, info)
  343. elif meta == 'struct':
  344. check_keys(expr, info, meta,
  345. ['struct', 'data'], ['base', 'if', 'features'])
  346. normalize_members(expr['data'])
  347. check_struct(expr, info)
  348. elif meta == 'command':
  349. check_keys(expr, info, meta,
  350. ['command'],
  351. ['data', 'returns', 'boxed', 'if', 'features',
  352. 'gen', 'success-response', 'allow-oob',
  353. 'allow-preconfig', 'coroutine'])
  354. normalize_members(expr.get('data'))
  355. check_command(expr, info)
  356. elif meta == 'event':
  357. check_keys(expr, info, meta,
  358. ['event'], ['data', 'boxed', 'if', 'features'])
  359. normalize_members(expr.get('data'))
  360. check_event(expr, info)
  361. else:
  362. assert False, 'unexpected meta type'
  363. check_if(expr, info, meta)
  364. check_features(expr.get('features'), info)
  365. check_flags(expr, info)
  366. return exprs