qapi.py 36 KB

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