qapi.py 37 KB

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