expr.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  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. def check_if_str(ifcond: object) -> None:
  123. if not isinstance(ifcond, str):
  124. raise QAPISemError(
  125. info,
  126. "'if' condition of %s must be a string or a list of strings"
  127. % source)
  128. if ifcond.strip() == '':
  129. raise QAPISemError(
  130. info,
  131. "'if' condition '%s' of %s makes no sense"
  132. % (ifcond, source))
  133. ifcond = expr.get('if')
  134. if ifcond is None:
  135. return
  136. if isinstance(ifcond, list):
  137. if ifcond == []:
  138. raise QAPISemError(
  139. info, "'if' condition [] of %s is useless" % source)
  140. for elt in ifcond:
  141. check_if_str(elt)
  142. else:
  143. check_if_str(ifcond)
  144. expr['if'] = [ifcond]
  145. def normalize_members(members: object) -> None:
  146. if isinstance(members, dict):
  147. for key, arg in members.items():
  148. if isinstance(arg, dict):
  149. continue
  150. members[key] = {'type': arg}
  151. def check_type(value: Optional[object],
  152. info: QAPISourceInfo,
  153. source: str,
  154. allow_array: bool = False,
  155. allow_dict: Union[bool, str] = False) -> None:
  156. if value is None:
  157. return
  158. # Type name
  159. if isinstance(value, str):
  160. return
  161. # Array type
  162. if isinstance(value, list):
  163. if not allow_array:
  164. raise QAPISemError(info, "%s cannot be an array" % source)
  165. if len(value) != 1 or not isinstance(value[0], str):
  166. raise QAPISemError(info,
  167. "%s: array type must contain single type name" %
  168. source)
  169. return
  170. # Anonymous type
  171. if not allow_dict:
  172. raise QAPISemError(info, "%s should be a type name" % source)
  173. if not isinstance(value, dict):
  174. raise QAPISemError(info,
  175. "%s should be an object or type name" % source)
  176. permissive = False
  177. if isinstance(allow_dict, str):
  178. permissive = allow_dict in info.pragma.member_name_exceptions
  179. # value is a dictionary, check that each member is okay
  180. for (key, arg) in value.items():
  181. key_source = "%s member '%s'" % (source, key)
  182. if key.startswith('*'):
  183. key = key[1:]
  184. check_name_lower(key, info, key_source,
  185. permit_upper=permissive,
  186. permit_underscore=permissive)
  187. if c_name(key, False) == 'u' or c_name(key, False).startswith('has_'):
  188. raise QAPISemError(info, "%s uses reserved name" % key_source)
  189. check_keys(arg, info, key_source, ['type'], ['if', 'features'])
  190. check_if(arg, info, key_source)
  191. check_features(arg.get('features'), info)
  192. check_type(arg['type'], info, key_source, allow_array=True)
  193. def check_features(features: Optional[object],
  194. info: QAPISourceInfo) -> None:
  195. if features is None:
  196. return
  197. if not isinstance(features, list):
  198. raise QAPISemError(info, "'features' must be an array")
  199. features[:] = [f if isinstance(f, dict) else {'name': f}
  200. for f in features]
  201. for f in features:
  202. source = "'features' member"
  203. assert isinstance(f, dict)
  204. check_keys(f, info, source, ['name'], ['if'])
  205. check_name_is_str(f['name'], info, source)
  206. source = "%s '%s'" % (source, f['name'])
  207. check_name_lower(f['name'], info, source)
  208. check_if(f, info, source)
  209. def check_enum(expr: _JSONObject, info: QAPISourceInfo) -> None:
  210. name = expr['enum']
  211. members = expr['data']
  212. prefix = expr.get('prefix')
  213. if not isinstance(members, list):
  214. raise QAPISemError(info, "'data' must be an array")
  215. if prefix is not None and not isinstance(prefix, str):
  216. raise QAPISemError(info, "'prefix' must be a string")
  217. permissive = name in info.pragma.member_name_exceptions
  218. members[:] = [m if isinstance(m, dict) else {'name': m}
  219. for m in members]
  220. for member in members:
  221. source = "'data' member"
  222. member_name = member['name']
  223. check_keys(member, info, source, ['name'], ['if'])
  224. check_name_is_str(member_name, info, source)
  225. source = "%s '%s'" % (source, member_name)
  226. # Enum members may start with a digit
  227. if member_name[0].isdigit():
  228. member_name = 'd' + member_name # Hack: hide the digit
  229. check_name_lower(member_name, info, source,
  230. permit_upper=permissive,
  231. permit_underscore=permissive)
  232. check_if(member, info, source)
  233. def check_struct(expr: _JSONObject, info: QAPISourceInfo) -> None:
  234. name = cast(str, expr['struct']) # Checked in check_exprs
  235. members = expr['data']
  236. check_type(members, info, "'data'", allow_dict=name)
  237. check_type(expr.get('base'), info, "'base'")
  238. def check_union(expr: _JSONObject, info: QAPISourceInfo) -> None:
  239. name = cast(str, expr['union']) # Checked in check_exprs
  240. base = expr.get('base')
  241. discriminator = expr.get('discriminator')
  242. members = expr['data']
  243. if discriminator is None: # simple union
  244. if base is not None:
  245. raise QAPISemError(info, "'base' requires 'discriminator'")
  246. else: # flat union
  247. check_type(base, info, "'base'", allow_dict=name)
  248. if not base:
  249. raise QAPISemError(info, "'discriminator' requires 'base'")
  250. check_name_is_str(discriminator, info, "'discriminator'")
  251. if not isinstance(members, dict):
  252. raise QAPISemError(info, "'data' must be an object")
  253. for (key, value) in members.items():
  254. source = "'data' member '%s'" % key
  255. if discriminator is None:
  256. check_name_lower(key, info, source)
  257. # else: name is in discriminator enum, which gets checked
  258. check_keys(value, info, source, ['type'], ['if'])
  259. check_if(value, info, source)
  260. check_type(value['type'], info, source, allow_array=not base)
  261. def check_alternate(expr: _JSONObject, info: QAPISourceInfo) -> None:
  262. members = expr['data']
  263. if not members:
  264. raise QAPISemError(info, "'data' must not be empty")
  265. if not isinstance(members, dict):
  266. raise QAPISemError(info, "'data' must be an object")
  267. for (key, value) in members.items():
  268. source = "'data' member '%s'" % key
  269. check_name_lower(key, info, source)
  270. check_keys(value, info, source, ['type'], ['if'])
  271. check_if(value, info, source)
  272. check_type(value['type'], info, source)
  273. def check_command(expr: _JSONObject, info: QAPISourceInfo) -> None:
  274. args = expr.get('data')
  275. rets = expr.get('returns')
  276. boxed = expr.get('boxed', False)
  277. if boxed and args is None:
  278. raise QAPISemError(info, "'boxed': true requires 'data'")
  279. check_type(args, info, "'data'", allow_dict=not boxed)
  280. check_type(rets, info, "'returns'", allow_array=True)
  281. def check_event(expr: _JSONObject, info: QAPISourceInfo) -> None:
  282. args = expr.get('data')
  283. boxed = expr.get('boxed', False)
  284. if boxed and args is None:
  285. raise QAPISemError(info, "'boxed': true requires 'data'")
  286. check_type(args, info, "'data'", allow_dict=not boxed)
  287. def check_exprs(exprs: List[_JSONObject]) -> List[_JSONObject]:
  288. for expr_elem in exprs:
  289. # Expression
  290. assert isinstance(expr_elem['expr'], dict)
  291. for key in expr_elem['expr'].keys():
  292. assert isinstance(key, str)
  293. expr: _JSONObject = expr_elem['expr']
  294. # QAPISourceInfo
  295. assert isinstance(expr_elem['info'], QAPISourceInfo)
  296. info: QAPISourceInfo = expr_elem['info']
  297. # Optional[QAPIDoc]
  298. tmp = expr_elem.get('doc')
  299. assert tmp is None or isinstance(tmp, QAPIDoc)
  300. doc: Optional[QAPIDoc] = tmp
  301. if 'include' in expr:
  302. continue
  303. if 'enum' in expr:
  304. meta = 'enum'
  305. elif 'union' in expr:
  306. meta = 'union'
  307. elif 'alternate' in expr:
  308. meta = 'alternate'
  309. elif 'struct' in expr:
  310. meta = 'struct'
  311. elif 'command' in expr:
  312. meta = 'command'
  313. elif 'event' in expr:
  314. meta = 'event'
  315. else:
  316. raise QAPISemError(info, "expression is missing metatype")
  317. check_name_is_str(expr[meta], info, "'%s'" % meta)
  318. name = cast(str, expr[meta])
  319. info.set_defn(meta, name)
  320. check_defn_name_str(name, info, meta)
  321. if doc:
  322. if doc.symbol != name:
  323. raise QAPISemError(
  324. info, "documentation comment is for '%s'" % doc.symbol)
  325. doc.check_expr(expr)
  326. elif info.pragma.doc_required:
  327. raise QAPISemError(info,
  328. "documentation comment required")
  329. if meta == 'enum':
  330. check_keys(expr, info, meta,
  331. ['enum', 'data'], ['if', 'features', 'prefix'])
  332. check_enum(expr, info)
  333. elif meta == 'union':
  334. check_keys(expr, info, meta,
  335. ['union', 'data'],
  336. ['base', 'discriminator', 'if', 'features'])
  337. normalize_members(expr.get('base'))
  338. normalize_members(expr['data'])
  339. check_union(expr, info)
  340. elif meta == 'alternate':
  341. check_keys(expr, info, meta,
  342. ['alternate', 'data'], ['if', 'features'])
  343. normalize_members(expr['data'])
  344. check_alternate(expr, info)
  345. elif meta == 'struct':
  346. check_keys(expr, info, meta,
  347. ['struct', 'data'], ['base', 'if', 'features'])
  348. normalize_members(expr['data'])
  349. check_struct(expr, info)
  350. elif meta == 'command':
  351. check_keys(expr, info, meta,
  352. ['command'],
  353. ['data', 'returns', 'boxed', 'if', 'features',
  354. 'gen', 'success-response', 'allow-oob',
  355. 'allow-preconfig', 'coroutine'])
  356. normalize_members(expr.get('data'))
  357. check_command(expr, info)
  358. elif meta == 'event':
  359. check_keys(expr, info, meta,
  360. ['event'], ['data', 'boxed', 'if', 'features'])
  361. normalize_members(expr.get('data'))
  362. check_event(expr, info)
  363. else:
  364. assert False, 'unexpected meta type'
  365. check_if(expr, info, meta)
  366. check_features(expr.get('features'), info)
  367. check_flags(expr, info)
  368. return exprs