qapi.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. #
  2. # QAPI helper library
  3. #
  4. # Copyright IBM, Corp. 2011
  5. # Copyright (c) 2013-2015 Red Hat Inc.
  6. #
  7. # Authors:
  8. # Anthony Liguori <aliguori@us.ibm.com>
  9. # Markus Armbruster <armbru@redhat.com>
  10. #
  11. # This work is licensed under the terms of the GNU GPL, version 2.
  12. # See the COPYING file in the top-level directory.
  13. import re
  14. from ordereddict import OrderedDict
  15. import errno
  16. import getopt
  17. import os
  18. import sys
  19. import string
  20. builtin_types = {
  21. 'str': 'QTYPE_QSTRING',
  22. 'int': 'QTYPE_QINT',
  23. 'number': 'QTYPE_QFLOAT',
  24. 'bool': 'QTYPE_QBOOL',
  25. 'int8': 'QTYPE_QINT',
  26. 'int16': 'QTYPE_QINT',
  27. 'int32': 'QTYPE_QINT',
  28. 'int64': 'QTYPE_QINT',
  29. 'uint8': 'QTYPE_QINT',
  30. 'uint16': 'QTYPE_QINT',
  31. 'uint32': 'QTYPE_QINT',
  32. 'uint64': 'QTYPE_QINT',
  33. 'size': 'QTYPE_QINT',
  34. }
  35. # Whitelist of commands allowed to return a non-dictionary
  36. returns_whitelist = [
  37. # From QMP:
  38. 'human-monitor-command',
  39. 'query-migrate-cache-size',
  40. 'query-tpm-models',
  41. 'query-tpm-types',
  42. 'ringbuf-read',
  43. # From QGA:
  44. 'guest-file-open',
  45. 'guest-fsfreeze-freeze',
  46. 'guest-fsfreeze-freeze-list',
  47. 'guest-fsfreeze-status',
  48. 'guest-fsfreeze-thaw',
  49. 'guest-get-time',
  50. 'guest-set-vcpus',
  51. 'guest-sync',
  52. 'guest-sync-delimited',
  53. # From qapi-schema-test:
  54. 'user_def_cmd3',
  55. ]
  56. enum_types = []
  57. struct_types = []
  58. union_types = []
  59. events = []
  60. all_names = {}
  61. def error_path(parent):
  62. res = ""
  63. while parent:
  64. res = ("In file included from %s:%d:\n" % (parent['file'],
  65. parent['line'])) + res
  66. parent = parent['parent']
  67. return res
  68. class QAPISchemaError(Exception):
  69. def __init__(self, schema, msg):
  70. self.fname = schema.fname
  71. self.msg = msg
  72. self.col = 1
  73. self.line = schema.line
  74. for ch in schema.src[schema.line_pos:schema.pos]:
  75. if ch == '\t':
  76. self.col = (self.col + 7) % 8 + 1
  77. else:
  78. self.col += 1
  79. self.info = schema.incl_info
  80. def __str__(self):
  81. return error_path(self.info) + \
  82. "%s:%d:%d: %s" % (self.fname, self.line, self.col, self.msg)
  83. class QAPIExprError(Exception):
  84. def __init__(self, expr_info, msg):
  85. self.info = expr_info
  86. self.msg = msg
  87. def __str__(self):
  88. return error_path(self.info['parent']) + \
  89. "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
  90. class QAPISchema:
  91. def __init__(self, fp, previously_included = [], incl_info = None):
  92. abs_fname = os.path.abspath(fp.name)
  93. fname = fp.name
  94. self.fname = fname
  95. previously_included.append(abs_fname)
  96. self.incl_info = incl_info
  97. self.src = fp.read()
  98. if self.src == '' or self.src[-1] != '\n':
  99. self.src += '\n'
  100. self.cursor = 0
  101. self.line = 1
  102. self.line_pos = 0
  103. self.exprs = []
  104. self.accept()
  105. while self.tok != None:
  106. expr_info = {'file': fname, 'line': self.line,
  107. 'parent': self.incl_info}
  108. expr = self.get_expr(False)
  109. if isinstance(expr, dict) and "include" in expr:
  110. if len(expr) != 1:
  111. raise QAPIExprError(expr_info, "Invalid 'include' directive")
  112. include = expr["include"]
  113. if not isinstance(include, str):
  114. raise QAPIExprError(expr_info,
  115. 'Expected a file name (string), got: %s'
  116. % include)
  117. incl_abs_fname = os.path.join(os.path.dirname(abs_fname),
  118. include)
  119. # catch inclusion cycle
  120. inf = expr_info
  121. while inf:
  122. if incl_abs_fname == os.path.abspath(inf['file']):
  123. raise QAPIExprError(expr_info, "Inclusion loop for %s"
  124. % include)
  125. inf = inf['parent']
  126. # skip multiple include of the same file
  127. if incl_abs_fname in previously_included:
  128. continue
  129. try:
  130. fobj = open(incl_abs_fname, 'r')
  131. except IOError, e:
  132. raise QAPIExprError(expr_info,
  133. '%s: %s' % (e.strerror, include))
  134. exprs_include = QAPISchema(fobj, previously_included,
  135. expr_info)
  136. self.exprs.extend(exprs_include.exprs)
  137. else:
  138. expr_elem = {'expr': expr,
  139. 'info': expr_info}
  140. self.exprs.append(expr_elem)
  141. def accept(self):
  142. while True:
  143. self.tok = self.src[self.cursor]
  144. self.pos = self.cursor
  145. self.cursor += 1
  146. self.val = None
  147. if self.tok == '#':
  148. self.cursor = self.src.find('\n', self.cursor)
  149. elif self.tok in ['{', '}', ':', ',', '[', ']']:
  150. return
  151. elif self.tok == "'":
  152. string = ''
  153. esc = False
  154. while True:
  155. ch = self.src[self.cursor]
  156. self.cursor += 1
  157. if ch == '\n':
  158. raise QAPISchemaError(self,
  159. 'Missing terminating "\'"')
  160. if esc:
  161. if ch == 'b':
  162. string += '\b'
  163. elif ch == 'f':
  164. string += '\f'
  165. elif ch == 'n':
  166. string += '\n'
  167. elif ch == 'r':
  168. string += '\r'
  169. elif ch == 't':
  170. string += '\t'
  171. elif ch == 'u':
  172. value = 0
  173. for x in range(0, 4):
  174. ch = self.src[self.cursor]
  175. self.cursor += 1
  176. if ch not in "0123456789abcdefABCDEF":
  177. raise QAPISchemaError(self,
  178. '\\u escape needs 4 '
  179. 'hex digits')
  180. value = (value << 4) + int(ch, 16)
  181. # If Python 2 and 3 didn't disagree so much on
  182. # how to handle Unicode, then we could allow
  183. # Unicode string defaults. But most of QAPI is
  184. # ASCII-only, so we aren't losing much for now.
  185. if not value or value > 0x7f:
  186. raise QAPISchemaError(self,
  187. 'For now, \\u escape '
  188. 'only supports non-zero '
  189. 'values up to \\u007f')
  190. string += chr(value)
  191. elif ch in "\\/'\"":
  192. string += ch
  193. else:
  194. raise QAPISchemaError(self,
  195. "Unknown escape \\%s" %ch)
  196. esc = False
  197. elif ch == "\\":
  198. esc = True
  199. elif ch == "'":
  200. self.val = string
  201. return
  202. else:
  203. string += ch
  204. elif self.tok in "tfn":
  205. val = self.src[self.cursor - 1:]
  206. if val.startswith("true"):
  207. self.val = True
  208. self.cursor += 3
  209. return
  210. elif val.startswith("false"):
  211. self.val = False
  212. self.cursor += 4
  213. return
  214. elif val.startswith("null"):
  215. self.val = None
  216. self.cursor += 3
  217. return
  218. elif self.tok == '\n':
  219. if self.cursor == len(self.src):
  220. self.tok = None
  221. return
  222. self.line += 1
  223. self.line_pos = self.cursor
  224. elif not self.tok.isspace():
  225. raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
  226. def get_members(self):
  227. expr = OrderedDict()
  228. if self.tok == '}':
  229. self.accept()
  230. return expr
  231. if self.tok != "'":
  232. raise QAPISchemaError(self, 'Expected string or "}"')
  233. while True:
  234. key = self.val
  235. self.accept()
  236. if self.tok != ':':
  237. raise QAPISchemaError(self, 'Expected ":"')
  238. self.accept()
  239. if key in expr:
  240. raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
  241. expr[key] = self.get_expr(True)
  242. if self.tok == '}':
  243. self.accept()
  244. return expr
  245. if self.tok != ',':
  246. raise QAPISchemaError(self, 'Expected "," or "}"')
  247. self.accept()
  248. if self.tok != "'":
  249. raise QAPISchemaError(self, 'Expected string')
  250. def get_values(self):
  251. expr = []
  252. if self.tok == ']':
  253. self.accept()
  254. return expr
  255. if not self.tok in "{['tfn":
  256. raise QAPISchemaError(self, 'Expected "{", "[", "]", string, '
  257. 'boolean or "null"')
  258. while True:
  259. expr.append(self.get_expr(True))
  260. if self.tok == ']':
  261. self.accept()
  262. return expr
  263. if self.tok != ',':
  264. raise QAPISchemaError(self, 'Expected "," or "]"')
  265. self.accept()
  266. def get_expr(self, nested):
  267. if self.tok != '{' and not nested:
  268. raise QAPISchemaError(self, 'Expected "{"')
  269. if self.tok == '{':
  270. self.accept()
  271. expr = self.get_members()
  272. elif self.tok == '[':
  273. self.accept()
  274. expr = self.get_values()
  275. elif self.tok in "'tfn":
  276. expr = self.val
  277. self.accept()
  278. else:
  279. raise QAPISchemaError(self, 'Expected "{", "[" or string')
  280. return expr
  281. def find_base_fields(base):
  282. base_struct_define = find_struct(base)
  283. if not base_struct_define:
  284. return None
  285. return base_struct_define['data']
  286. # Return the qtype of an alternate branch, or None on error.
  287. def find_alternate_member_qtype(qapi_type):
  288. if builtin_types.has_key(qapi_type):
  289. return builtin_types[qapi_type]
  290. elif find_struct(qapi_type):
  291. return "QTYPE_QDICT"
  292. elif find_enum(qapi_type):
  293. return "QTYPE_QSTRING"
  294. elif find_union(qapi_type):
  295. return "QTYPE_QDICT"
  296. return None
  297. # Return the discriminator enum define if discriminator is specified as an
  298. # enum type, otherwise return None.
  299. def discriminator_find_enum_define(expr):
  300. base = expr.get('base')
  301. discriminator = expr.get('discriminator')
  302. if not (discriminator and base):
  303. return None
  304. base_fields = find_base_fields(base)
  305. if not base_fields:
  306. return None
  307. discriminator_type = base_fields.get(discriminator)
  308. if not discriminator_type:
  309. return None
  310. return find_enum(discriminator_type)
  311. valid_name = re.compile('^[a-zA-Z_][a-zA-Z0-9_.-]*$')
  312. def check_name(expr_info, source, name, allow_optional = False,
  313. enum_member = False):
  314. global valid_name
  315. membername = name
  316. if not isinstance(name, str):
  317. raise QAPIExprError(expr_info,
  318. "%s requires a string name" % source)
  319. if name.startswith('*'):
  320. membername = name[1:]
  321. if not allow_optional:
  322. raise QAPIExprError(expr_info,
  323. "%s does not allow optional name '%s'"
  324. % (source, name))
  325. # Enum members can start with a digit, because the generated C
  326. # code always prefixes it with the enum name
  327. if enum_member:
  328. membername = '_' + membername
  329. if not valid_name.match(membername):
  330. raise QAPIExprError(expr_info,
  331. "%s uses invalid name '%s'" % (source, name))
  332. def check_type(expr_info, source, value, allow_array = False,
  333. allow_dict = False, allow_optional = False,
  334. allow_star = False, allow_metas = []):
  335. global all_names
  336. orig_value = value
  337. if value is None:
  338. return
  339. if allow_star and value == '**':
  340. return
  341. # Check if array type for value is okay
  342. if isinstance(value, list):
  343. if not allow_array:
  344. raise QAPIExprError(expr_info,
  345. "%s cannot be an array" % source)
  346. if len(value) != 1 or not isinstance(value[0], str):
  347. raise QAPIExprError(expr_info,
  348. "%s: array type must contain single type name"
  349. % source)
  350. value = value[0]
  351. orig_value = "array of %s" %value
  352. # Check if type name for value is okay
  353. if isinstance(value, str):
  354. if value == '**':
  355. raise QAPIExprError(expr_info,
  356. "%s uses '**' but did not request 'gen':false"
  357. % source)
  358. if not value in all_names:
  359. raise QAPIExprError(expr_info,
  360. "%s uses unknown type '%s'"
  361. % (source, orig_value))
  362. if not all_names[value] in allow_metas:
  363. raise QAPIExprError(expr_info,
  364. "%s cannot use %s type '%s'"
  365. % (source, all_names[value], orig_value))
  366. return
  367. # value is a dictionary, check that each member is okay
  368. if not isinstance(value, OrderedDict):
  369. raise QAPIExprError(expr_info,
  370. "%s should be a dictionary" % source)
  371. if not allow_dict:
  372. raise QAPIExprError(expr_info,
  373. "%s should be a type name" % source)
  374. for (key, arg) in value.items():
  375. check_name(expr_info, "Member of %s" % source, key,
  376. allow_optional=allow_optional)
  377. # Todo: allow dictionaries to represent default values of
  378. # an optional argument.
  379. check_type(expr_info, "Member '%s' of %s" % (key, source), arg,
  380. allow_array=True, allow_star=allow_star,
  381. allow_metas=['built-in', 'union', 'alternate', 'struct',
  382. 'enum'])
  383. def check_member_clash(expr_info, base_name, data, source = ""):
  384. base = find_struct(base_name)
  385. assert base
  386. base_members = base['data']
  387. for key in data.keys():
  388. if key.startswith('*'):
  389. key = key[1:]
  390. if key in base_members or "*" + key in base_members:
  391. raise QAPIExprError(expr_info,
  392. "Member name '%s'%s clashes with base '%s'"
  393. % (key, source, base_name))
  394. if base.get('base'):
  395. check_member_clash(expr_info, base['base'], data, source)
  396. def check_command(expr, expr_info):
  397. name = expr['command']
  398. allow_star = expr.has_key('gen')
  399. check_type(expr_info, "'data' for command '%s'" % name,
  400. expr.get('data'), allow_dict=True, allow_optional=True,
  401. allow_metas=['union', 'struct'], allow_star=allow_star)
  402. returns_meta = ['union', 'struct']
  403. if name in returns_whitelist:
  404. returns_meta += ['built-in', 'alternate', 'enum']
  405. check_type(expr_info, "'returns' for command '%s'" % name,
  406. expr.get('returns'), allow_array=True, allow_dict=True,
  407. allow_optional=True, allow_metas=returns_meta,
  408. allow_star=allow_star)
  409. def check_event(expr, expr_info):
  410. global events
  411. name = expr['event']
  412. params = expr.get('data')
  413. if name.upper() == 'MAX':
  414. raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created")
  415. events.append(name)
  416. check_type(expr_info, "'data' for event '%s'" % name,
  417. expr.get('data'), allow_dict=True, allow_optional=True,
  418. allow_metas=['union', 'struct'])
  419. def check_union(expr, expr_info):
  420. name = expr['union']
  421. base = expr.get('base')
  422. discriminator = expr.get('discriminator')
  423. members = expr['data']
  424. values = { 'MAX': '(automatic)' }
  425. # If the object has a member 'base', its value must name a struct,
  426. # and there must be a discriminator.
  427. if base is not None:
  428. if discriminator is None:
  429. raise QAPIExprError(expr_info,
  430. "Union '%s' requires a discriminator to go "
  431. "along with base" %name)
  432. # Two types of unions, determined by discriminator.
  433. # With no discriminator it is a simple union.
  434. if discriminator is None:
  435. enum_define = None
  436. allow_metas=['built-in', 'union', 'alternate', 'struct', 'enum']
  437. if base is not None:
  438. raise QAPIExprError(expr_info,
  439. "Simple union '%s' must not have a base"
  440. % name)
  441. # Else, it's a flat union.
  442. else:
  443. # The object must have a string member 'base'.
  444. if not isinstance(base, str):
  445. raise QAPIExprError(expr_info,
  446. "Flat union '%s' must have a string base field"
  447. % name)
  448. base_fields = find_base_fields(base)
  449. if not base_fields:
  450. raise QAPIExprError(expr_info,
  451. "Base '%s' is not a valid struct"
  452. % base)
  453. # The value of member 'discriminator' must name a non-optional
  454. # member of the base struct.
  455. check_name(expr_info, "Discriminator of flat union '%s'" % name,
  456. discriminator)
  457. discriminator_type = base_fields.get(discriminator)
  458. if not discriminator_type:
  459. raise QAPIExprError(expr_info,
  460. "Discriminator '%s' is not a member of base "
  461. "struct '%s'"
  462. % (discriminator, base))
  463. enum_define = find_enum(discriminator_type)
  464. allow_metas=['struct']
  465. # Do not allow string discriminator
  466. if not enum_define:
  467. raise QAPIExprError(expr_info,
  468. "Discriminator '%s' must be of enumeration "
  469. "type" % discriminator)
  470. # Check every branch
  471. for (key, value) in members.items():
  472. check_name(expr_info, "Member of union '%s'" % name, key)
  473. # Each value must name a known type; furthermore, in flat unions,
  474. # branches must be a struct with no overlapping member names
  475. check_type(expr_info, "Member '%s' of union '%s'" % (key, name),
  476. value, allow_array=True, allow_metas=allow_metas)
  477. if base:
  478. branch_struct = find_struct(value)
  479. assert branch_struct
  480. check_member_clash(expr_info, base, branch_struct['data'],
  481. " of branch '%s'" % key)
  482. # If the discriminator names an enum type, then all members
  483. # of 'data' must also be members of the enum type.
  484. if enum_define:
  485. if not key in enum_define['enum_values']:
  486. raise QAPIExprError(expr_info,
  487. "Discriminator value '%s' is not found in "
  488. "enum '%s'" %
  489. (key, enum_define["enum_name"]))
  490. # Otherwise, check for conflicts in the generated enum
  491. else:
  492. c_key = camel_to_upper(key)
  493. if c_key in values:
  494. raise QAPIExprError(expr_info,
  495. "Union '%s' member '%s' clashes with '%s'"
  496. % (name, key, values[c_key]))
  497. values[c_key] = key
  498. def check_alternate(expr, expr_info):
  499. name = expr['alternate']
  500. members = expr['data']
  501. values = { 'MAX': '(automatic)' }
  502. types_seen = {}
  503. # Check every branch
  504. for (key, value) in members.items():
  505. check_name(expr_info, "Member of alternate '%s'" % name, key)
  506. # Check for conflicts in the generated enum
  507. c_key = camel_to_upper(key)
  508. if c_key in values:
  509. raise QAPIExprError(expr_info,
  510. "Alternate '%s' member '%s' clashes with '%s'"
  511. % (name, key, values[c_key]))
  512. values[c_key] = key
  513. # Ensure alternates have no type conflicts.
  514. check_type(expr_info, "Member '%s' of alternate '%s'" % (key, name),
  515. value,
  516. allow_metas=['built-in', 'union', 'struct', 'enum'])
  517. qtype = find_alternate_member_qtype(value)
  518. assert qtype
  519. if qtype in types_seen:
  520. raise QAPIExprError(expr_info,
  521. "Alternate '%s' member '%s' can't "
  522. "be distinguished from member '%s'"
  523. % (name, key, types_seen[qtype]))
  524. types_seen[qtype] = key
  525. def check_enum(expr, expr_info):
  526. name = expr['enum']
  527. members = expr.get('data')
  528. values = { 'MAX': '(automatic)' }
  529. if not isinstance(members, list):
  530. raise QAPIExprError(expr_info,
  531. "Enum '%s' requires an array for 'data'" % name)
  532. for member in members:
  533. check_name(expr_info, "Member of enum '%s'" %name, member,
  534. enum_member=True)
  535. key = camel_to_upper(member)
  536. if key in values:
  537. raise QAPIExprError(expr_info,
  538. "Enum '%s' member '%s' clashes with '%s'"
  539. % (name, member, values[key]))
  540. values[key] = member
  541. def check_struct(expr, expr_info):
  542. name = expr['struct']
  543. members = expr['data']
  544. check_type(expr_info, "'data' for struct '%s'" % name, members,
  545. allow_dict=True, allow_optional=True)
  546. check_type(expr_info, "'base' for struct '%s'" % name, expr.get('base'),
  547. allow_metas=['struct'])
  548. if expr.get('base'):
  549. check_member_clash(expr_info, expr['base'], expr['data'])
  550. def check_exprs(schema):
  551. for expr_elem in schema.exprs:
  552. expr = expr_elem['expr']
  553. info = expr_elem['info']
  554. if expr.has_key('enum'):
  555. check_enum(expr, info)
  556. elif expr.has_key('union'):
  557. check_union(expr, info)
  558. elif expr.has_key('alternate'):
  559. check_alternate(expr, info)
  560. elif expr.has_key('struct'):
  561. check_struct(expr, info)
  562. elif expr.has_key('command'):
  563. check_command(expr, info)
  564. elif expr.has_key('event'):
  565. check_event(expr, info)
  566. else:
  567. assert False, 'unexpected meta type'
  568. def check_keys(expr_elem, meta, required, optional=[]):
  569. expr = expr_elem['expr']
  570. info = expr_elem['info']
  571. name = expr[meta]
  572. if not isinstance(name, str):
  573. raise QAPIExprError(info,
  574. "'%s' key must have a string value" % meta)
  575. required = required + [ meta ]
  576. for (key, value) in expr.items():
  577. if not key in required and not key in optional:
  578. raise QAPIExprError(info,
  579. "Unknown key '%s' in %s '%s'"
  580. % (key, meta, name))
  581. if (key == 'gen' or key == 'success-response') and value != False:
  582. raise QAPIExprError(info,
  583. "'%s' of %s '%s' should only use false value"
  584. % (key, meta, name))
  585. for key in required:
  586. if not expr.has_key(key):
  587. raise QAPIExprError(info,
  588. "Key '%s' is missing from %s '%s'"
  589. % (key, meta, name))
  590. def parse_schema(fname):
  591. global all_names
  592. exprs = []
  593. # First pass: read entire file into memory
  594. try:
  595. schema = QAPISchema(open(fname, "r"))
  596. except (QAPISchemaError, QAPIExprError), e:
  597. print >>sys.stderr, e
  598. exit(1)
  599. try:
  600. # Next pass: learn the types and check for valid expression keys. At
  601. # this point, top-level 'include' has already been flattened.
  602. for builtin in builtin_types.keys():
  603. all_names[builtin] = 'built-in'
  604. for expr_elem in schema.exprs:
  605. expr = expr_elem['expr']
  606. info = expr_elem['info']
  607. if expr.has_key('enum'):
  608. check_keys(expr_elem, 'enum', ['data'])
  609. add_enum(expr['enum'], info, expr['data'])
  610. elif expr.has_key('union'):
  611. check_keys(expr_elem, 'union', ['data'],
  612. ['base', 'discriminator'])
  613. add_union(expr, info)
  614. elif expr.has_key('alternate'):
  615. check_keys(expr_elem, 'alternate', ['data'])
  616. add_name(expr['alternate'], info, 'alternate')
  617. elif expr.has_key('struct'):
  618. check_keys(expr_elem, 'struct', ['data'], ['base'])
  619. add_struct(expr, info)
  620. elif expr.has_key('command'):
  621. check_keys(expr_elem, 'command', [],
  622. ['data', 'returns', 'gen', 'success-response'])
  623. add_name(expr['command'], info, 'command')
  624. elif expr.has_key('event'):
  625. check_keys(expr_elem, 'event', [], ['data'])
  626. add_name(expr['event'], info, 'event')
  627. else:
  628. raise QAPIExprError(expr_elem['info'],
  629. "Expression is missing metatype")
  630. exprs.append(expr)
  631. # Try again for hidden UnionKind enum
  632. for expr_elem in schema.exprs:
  633. expr = expr_elem['expr']
  634. if expr.has_key('union'):
  635. if not discriminator_find_enum_define(expr):
  636. add_enum('%sKind' % expr['union'], expr_elem['info'],
  637. implicit=True)
  638. elif expr.has_key('alternate'):
  639. add_enum('%sKind' % expr['alternate'], expr_elem['info'],
  640. implicit=True)
  641. # Final pass - validate that exprs make sense
  642. check_exprs(schema)
  643. except QAPIExprError, e:
  644. print >>sys.stderr, e
  645. exit(1)
  646. return exprs
  647. def parse_args(typeinfo):
  648. if isinstance(typeinfo, str):
  649. struct = find_struct(typeinfo)
  650. assert struct != None
  651. typeinfo = struct['data']
  652. for member in typeinfo:
  653. argname = member
  654. argentry = typeinfo[member]
  655. optional = False
  656. if member.startswith('*'):
  657. argname = member[1:]
  658. optional = True
  659. # Todo: allow argentry to be OrderedDict, for providing the
  660. # value of an optional argument.
  661. yield (argname, argentry, optional)
  662. def camel_case(name):
  663. new_name = ''
  664. first = True
  665. for ch in name:
  666. if ch in ['_', '-']:
  667. first = True
  668. elif first:
  669. new_name += ch.upper()
  670. first = False
  671. else:
  672. new_name += ch.lower()
  673. return new_name
  674. # ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
  675. # ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
  676. # ENUM24_Name -> ENUM24_NAME
  677. def camel_to_upper(value):
  678. c_fun_str = c_name(value, False)
  679. if value.isupper():
  680. return c_fun_str
  681. new_name = ''
  682. l = len(c_fun_str)
  683. for i in range(l):
  684. c = c_fun_str[i]
  685. # When c is upper and no "_" appears before, do more checks
  686. if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
  687. # Case 1: next string is lower
  688. # Case 2: previous string is digit
  689. if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
  690. c_fun_str[i - 1].isdigit():
  691. new_name += '_'
  692. new_name += c
  693. return new_name.lstrip('_').upper()
  694. def c_enum_const(type_name, const_name):
  695. return camel_to_upper(type_name + '_' + const_name)
  696. c_name_trans = string.maketrans('.-', '__')
  697. # Map @name to a valid C identifier.
  698. # If @protect, avoid returning certain ticklish identifiers (like
  699. # C keywords) by prepending "q_".
  700. #
  701. # Used for converting 'name' from a 'name':'type' qapi definition
  702. # into a generated struct member, as well as converting type names
  703. # into substrings of a generated C function name.
  704. # '__a.b_c' -> '__a_b_c', 'x-foo' -> 'x_foo'
  705. # protect=True: 'int' -> 'q_int'; protect=False: 'int' -> 'int'
  706. def c_name(name, protect=True):
  707. # ANSI X3J11/88-090, 3.1.1
  708. c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
  709. 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
  710. 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
  711. 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
  712. 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
  713. # ISO/IEC 9899:1999, 6.4.1
  714. c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
  715. # ISO/IEC 9899:2011, 6.4.1
  716. c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
  717. '_Static_assert', '_Thread_local'])
  718. # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
  719. # excluding _.*
  720. gcc_words = set(['asm', 'typeof'])
  721. # C++ ISO/IEC 14882:2003 2.11
  722. cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
  723. 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
  724. 'namespace', 'new', 'operator', 'private', 'protected',
  725. 'public', 'reinterpret_cast', 'static_cast', 'template',
  726. 'this', 'throw', 'true', 'try', 'typeid', 'typename',
  727. 'using', 'virtual', 'wchar_t',
  728. # alternative representations
  729. 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
  730. 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
  731. # namespace pollution:
  732. polluted_words = set(['unix', 'errno'])
  733. if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
  734. return "q_" + name
  735. return name.translate(c_name_trans)
  736. # Map type @name to the C typedef name for the list form.
  737. #
  738. # ['Name'] -> 'NameList', ['x-Foo'] -> 'x_FooList', ['int'] -> 'intList'
  739. def c_list_type(name):
  740. return type_name(name) + 'List'
  741. # Map type @value to the C typedef form.
  742. #
  743. # Used for converting 'type' from a 'member':'type' qapi definition
  744. # into the alphanumeric portion of the type for a generated C parameter,
  745. # as well as generated C function names. See c_type() for the rest of
  746. # the conversion such as adding '*' on pointer types.
  747. # 'int' -> 'int', '[x-Foo]' -> 'x_FooList', '__a.b_c' -> '__a_b_c'
  748. def type_name(value):
  749. if type(value) == list:
  750. return c_list_type(value[0])
  751. if value in builtin_types.keys():
  752. return value
  753. return c_name(value)
  754. def add_name(name, info, meta, implicit = False):
  755. global all_names
  756. check_name(info, "'%s'" % meta, name)
  757. if name in all_names:
  758. raise QAPIExprError(info,
  759. "%s '%s' is already defined"
  760. % (all_names[name], name))
  761. if not implicit and name[-4:] == 'Kind':
  762. raise QAPIExprError(info,
  763. "%s '%s' should not end in 'Kind'"
  764. % (meta, name))
  765. all_names[name] = meta
  766. def add_struct(definition, info):
  767. global struct_types
  768. name = definition['struct']
  769. add_name(name, info, 'struct')
  770. struct_types.append(definition)
  771. def find_struct(name):
  772. global struct_types
  773. for struct in struct_types:
  774. if struct['struct'] == name:
  775. return struct
  776. return None
  777. def add_union(definition, info):
  778. global union_types
  779. name = definition['union']
  780. add_name(name, info, 'union')
  781. union_types.append(definition)
  782. def find_union(name):
  783. global union_types
  784. for union in union_types:
  785. if union['union'] == name:
  786. return union
  787. return None
  788. def add_enum(name, info, enum_values = None, implicit = False):
  789. global enum_types
  790. add_name(name, info, 'enum', implicit)
  791. enum_types.append({"enum_name": name, "enum_values": enum_values})
  792. def find_enum(name):
  793. global enum_types
  794. for enum in enum_types:
  795. if enum['enum_name'] == name:
  796. return enum
  797. return None
  798. def is_enum(name):
  799. return find_enum(name) != None
  800. eatspace = '\033EATSPACE.'
  801. pointer_suffix = ' *' + eatspace
  802. # Map type @name to its C type expression.
  803. # If @is_param, const-qualify the string type.
  804. #
  805. # This function is used for computing the full C type of 'member':'name'.
  806. # A special suffix is added in c_type() for pointer types, and it's
  807. # stripped in mcgen(). So please notice this when you check the return
  808. # value of c_type() outside mcgen().
  809. def c_type(value, is_param=False):
  810. if value == 'str':
  811. if is_param:
  812. return 'const char' + pointer_suffix
  813. return 'char' + pointer_suffix
  814. elif value == 'int':
  815. return 'int64_t'
  816. elif (value == 'int8' or value == 'int16' or value == 'int32' or
  817. value == 'int64' or value == 'uint8' or value == 'uint16' or
  818. value == 'uint32' or value == 'uint64'):
  819. return value + '_t'
  820. elif value == 'size':
  821. return 'uint64_t'
  822. elif value == 'bool':
  823. return 'bool'
  824. elif value == 'number':
  825. return 'double'
  826. elif type(value) == list:
  827. return c_list_type(value[0]) + pointer_suffix
  828. elif is_enum(value):
  829. return c_name(value)
  830. elif value == None:
  831. return 'void'
  832. elif value in events:
  833. return camel_case(value) + 'Event' + pointer_suffix
  834. else:
  835. # complex type name
  836. assert isinstance(value, str) and value != ""
  837. return c_name(value) + pointer_suffix
  838. def is_c_ptr(value):
  839. return c_type(value).endswith(pointer_suffix)
  840. def genindent(count):
  841. ret = ""
  842. for i in range(count):
  843. ret += " "
  844. return ret
  845. indent_level = 0
  846. def push_indent(indent_amount=4):
  847. global indent_level
  848. indent_level += indent_amount
  849. def pop_indent(indent_amount=4):
  850. global indent_level
  851. indent_level -= indent_amount
  852. def cgen(code, **kwds):
  853. indent = genindent(indent_level)
  854. lines = code.split('\n')
  855. lines = map(lambda x: indent + x, lines)
  856. return '\n'.join(lines) % kwds + '\n'
  857. def mcgen(code, **kwds):
  858. raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
  859. return re.sub(re.escape(eatspace) + ' *', '', raw)
  860. def basename(filename):
  861. return filename.split("/")[-1]
  862. def guardname(filename):
  863. guard = basename(filename).rsplit(".", 1)[0]
  864. for substr in [".", " ", "-"]:
  865. guard = guard.replace(substr, "_")
  866. return guard.upper() + '_H'
  867. def guardstart(name):
  868. return mcgen('''
  869. #ifndef %(name)s
  870. #define %(name)s
  871. ''',
  872. name=guardname(name))
  873. def guardend(name):
  874. return mcgen('''
  875. #endif /* %(name)s */
  876. ''',
  877. name=guardname(name))
  878. def parse_command_line(extra_options = "", extra_long_options = []):
  879. try:
  880. opts, args = getopt.gnu_getopt(sys.argv[1:],
  881. "chp:o:" + extra_options,
  882. ["source", "header", "prefix=",
  883. "output-dir="] + extra_long_options)
  884. except getopt.GetoptError, err:
  885. print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
  886. sys.exit(1)
  887. output_dir = ""
  888. prefix = ""
  889. do_c = False
  890. do_h = False
  891. extra_opts = []
  892. for oa in opts:
  893. o, a = oa
  894. if o in ("-p", "--prefix"):
  895. prefix = a
  896. elif o in ("-o", "--output-dir"):
  897. output_dir = a + "/"
  898. elif o in ("-c", "--source"):
  899. do_c = True
  900. elif o in ("-h", "--header"):
  901. do_h = True
  902. else:
  903. extra_opts.append(oa)
  904. if not do_c and not do_h:
  905. do_c = True
  906. do_h = True
  907. if len(args) != 1:
  908. print >>sys.stderr, "%s: need exactly one argument" % sys.argv[0]
  909. sys.exit(1)
  910. fname = args[0]
  911. return (fname, output_dir, do_c, do_h, prefix, extra_opts)
  912. def open_output(output_dir, do_c, do_h, prefix, c_file, h_file,
  913. c_comment, h_comment):
  914. c_file = output_dir + prefix + c_file
  915. h_file = output_dir + prefix + h_file
  916. try:
  917. os.makedirs(output_dir)
  918. except os.error, e:
  919. if e.errno != errno.EEXIST:
  920. raise
  921. def maybe_open(really, name, opt):
  922. if really:
  923. return open(name, opt)
  924. else:
  925. import StringIO
  926. return StringIO.StringIO()
  927. fdef = maybe_open(do_c, c_file, 'w')
  928. fdecl = maybe_open(do_h, h_file, 'w')
  929. fdef.write(mcgen('''
  930. /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
  931. %(comment)s
  932. ''',
  933. comment = c_comment))
  934. fdecl.write(mcgen('''
  935. /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
  936. %(comment)s
  937. #ifndef %(guard)s
  938. #define %(guard)s
  939. ''',
  940. comment = h_comment, guard = guardname(h_file)))
  941. return (fdef, fdecl)
  942. def close_output(fdef, fdecl):
  943. fdecl.write('''
  944. #endif
  945. ''')
  946. fdecl.close()
  947. fdef.close()