2
0

expr.py 14 KB

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