qapi.py 37 KB

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