qapi.py 37 KB

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