qapi.py 37 KB

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