qapi.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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 os
  16. import sys
  17. builtin_types = {
  18. 'str': 'QTYPE_QSTRING',
  19. 'int': 'QTYPE_QINT',
  20. 'number': 'QTYPE_QFLOAT',
  21. 'bool': 'QTYPE_QBOOL',
  22. 'int8': 'QTYPE_QINT',
  23. 'int16': 'QTYPE_QINT',
  24. 'int32': 'QTYPE_QINT',
  25. 'int64': 'QTYPE_QINT',
  26. 'uint8': 'QTYPE_QINT',
  27. 'uint16': 'QTYPE_QINT',
  28. 'uint32': 'QTYPE_QINT',
  29. 'uint64': 'QTYPE_QINT',
  30. 'size': 'QTYPE_QINT',
  31. }
  32. def error_path(parent):
  33. res = ""
  34. while parent:
  35. res = ("In file included from %s:%d:\n" % (parent['file'],
  36. parent['line'])) + res
  37. parent = parent['parent']
  38. return res
  39. class QAPISchemaError(Exception):
  40. def __init__(self, schema, msg):
  41. self.input_file = schema.input_file
  42. self.msg = msg
  43. self.col = 1
  44. self.line = schema.line
  45. for ch in schema.src[schema.line_pos:schema.pos]:
  46. if ch == '\t':
  47. self.col = (self.col + 7) % 8 + 1
  48. else:
  49. self.col += 1
  50. self.info = schema.parent_info
  51. def __str__(self):
  52. return error_path(self.info) + \
  53. "%s:%d:%d: %s" % (self.input_file, self.line, self.col, self.msg)
  54. class QAPIExprError(Exception):
  55. def __init__(self, expr_info, msg):
  56. self.info = expr_info
  57. self.msg = msg
  58. def __str__(self):
  59. return error_path(self.info['parent']) + \
  60. "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
  61. class QAPISchema:
  62. def __init__(self, fp, input_relname=None, include_hist=[],
  63. previously_included=[], parent_info=None):
  64. """ include_hist is a stack used to detect inclusion cycles
  65. previously_included is a global state used to avoid multiple
  66. inclusions of the same file"""
  67. input_fname = os.path.abspath(fp.name)
  68. if input_relname is None:
  69. input_relname = fp.name
  70. self.input_dir = os.path.dirname(input_fname)
  71. self.input_file = input_relname
  72. self.include_hist = include_hist + [(input_relname, input_fname)]
  73. previously_included.append(input_fname)
  74. self.parent_info = parent_info
  75. self.src = fp.read()
  76. if self.src == '' or self.src[-1] != '\n':
  77. self.src += '\n'
  78. self.cursor = 0
  79. self.line = 1
  80. self.line_pos = 0
  81. self.exprs = []
  82. self.accept()
  83. while self.tok != None:
  84. expr_info = {'file': input_relname, 'line': self.line, 'parent': self.parent_info}
  85. expr = self.get_expr(False)
  86. if isinstance(expr, dict) and "include" in expr:
  87. if len(expr) != 1:
  88. raise QAPIExprError(expr_info, "Invalid 'include' directive")
  89. include = expr["include"]
  90. if not isinstance(include, str):
  91. raise QAPIExprError(expr_info,
  92. 'Expected a file name (string), got: %s'
  93. % include)
  94. include_path = os.path.join(self.input_dir, include)
  95. for elem in self.include_hist:
  96. if include_path == elem[1]:
  97. raise QAPIExprError(expr_info, "Inclusion loop for %s"
  98. % include)
  99. # skip multiple include of the same file
  100. if include_path in previously_included:
  101. continue
  102. try:
  103. fobj = open(include_path, 'r')
  104. except IOError, e:
  105. raise QAPIExprError(expr_info,
  106. '%s: %s' % (e.strerror, include))
  107. exprs_include = QAPISchema(fobj, include, self.include_hist,
  108. previously_included, expr_info)
  109. self.exprs.extend(exprs_include.exprs)
  110. else:
  111. expr_elem = {'expr': expr,
  112. 'info': expr_info}
  113. self.exprs.append(expr_elem)
  114. def accept(self):
  115. while True:
  116. self.tok = self.src[self.cursor]
  117. self.pos = self.cursor
  118. self.cursor += 1
  119. self.val = None
  120. if self.tok == '#':
  121. self.cursor = self.src.find('\n', self.cursor)
  122. elif self.tok in ['{', '}', ':', ',', '[', ']']:
  123. return
  124. elif self.tok == "'":
  125. string = ''
  126. esc = False
  127. while True:
  128. ch = self.src[self.cursor]
  129. self.cursor += 1
  130. if ch == '\n':
  131. raise QAPISchemaError(self,
  132. 'Missing terminating "\'"')
  133. if esc:
  134. string += ch
  135. esc = False
  136. elif ch == "\\":
  137. esc = True
  138. elif ch == "'":
  139. self.val = string
  140. return
  141. else:
  142. string += ch
  143. elif self.tok == '\n':
  144. if self.cursor == len(self.src):
  145. self.tok = None
  146. return
  147. self.line += 1
  148. self.line_pos = self.cursor
  149. elif not self.tok.isspace():
  150. raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
  151. def get_members(self):
  152. expr = OrderedDict()
  153. if self.tok == '}':
  154. self.accept()
  155. return expr
  156. if self.tok != "'":
  157. raise QAPISchemaError(self, 'Expected string or "}"')
  158. while True:
  159. key = self.val
  160. self.accept()
  161. if self.tok != ':':
  162. raise QAPISchemaError(self, 'Expected ":"')
  163. self.accept()
  164. if key in expr:
  165. raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
  166. expr[key] = self.get_expr(True)
  167. if self.tok == '}':
  168. self.accept()
  169. return expr
  170. if self.tok != ',':
  171. raise QAPISchemaError(self, 'Expected "," or "}"')
  172. self.accept()
  173. if self.tok != "'":
  174. raise QAPISchemaError(self, 'Expected string')
  175. def get_values(self):
  176. expr = []
  177. if self.tok == ']':
  178. self.accept()
  179. return expr
  180. if not self.tok in [ '{', '[', "'" ]:
  181. raise QAPISchemaError(self, 'Expected "{", "[", "]" or string')
  182. while True:
  183. expr.append(self.get_expr(True))
  184. if self.tok == ']':
  185. self.accept()
  186. return expr
  187. if self.tok != ',':
  188. raise QAPISchemaError(self, 'Expected "," or "]"')
  189. self.accept()
  190. def get_expr(self, nested):
  191. if self.tok != '{' and not nested:
  192. raise QAPISchemaError(self, 'Expected "{"')
  193. if self.tok == '{':
  194. self.accept()
  195. expr = self.get_members()
  196. elif self.tok == '[':
  197. self.accept()
  198. expr = self.get_values()
  199. elif self.tok == "'":
  200. expr = self.val
  201. self.accept()
  202. else:
  203. raise QAPISchemaError(self, 'Expected "{", "[" or string')
  204. return expr
  205. def find_base_fields(base):
  206. base_struct_define = find_struct(base)
  207. if not base_struct_define:
  208. return None
  209. return base_struct_define['data']
  210. # Return the qtype of an anonymous union branch, or None on error.
  211. def find_anonymous_member_qtype(qapi_type):
  212. if builtin_types.has_key(qapi_type):
  213. return builtin_types[qapi_type]
  214. elif find_struct(qapi_type):
  215. return "QTYPE_QDICT"
  216. elif find_enum(qapi_type):
  217. return "QTYPE_QSTRING"
  218. else:
  219. union = find_union(qapi_type)
  220. if union:
  221. discriminator = union.get('discriminator')
  222. if discriminator == {}:
  223. return None
  224. return "QTYPE_QDICT"
  225. return None
  226. # Return the discriminator enum define if discriminator is specified as an
  227. # enum type, otherwise return None.
  228. def discriminator_find_enum_define(expr):
  229. base = expr.get('base')
  230. discriminator = expr.get('discriminator')
  231. if not (discriminator and base):
  232. return None
  233. base_fields = find_base_fields(base)
  234. if not base_fields:
  235. return None
  236. discriminator_type = base_fields.get(discriminator)
  237. if not discriminator_type:
  238. return None
  239. return find_enum(discriminator_type)
  240. def check_event(expr, expr_info):
  241. params = expr.get('data')
  242. if params:
  243. for argname, argentry, optional, structured in parse_args(params):
  244. if structured:
  245. raise QAPIExprError(expr_info,
  246. "Nested structure define in event is not "
  247. "supported, event '%s', argname '%s'"
  248. % (expr['event'], argname))
  249. def check_union(expr, expr_info):
  250. name = expr['union']
  251. base = expr.get('base')
  252. discriminator = expr.get('discriminator')
  253. members = expr['data']
  254. values = { 'MAX': '(automatic)' }
  255. types_seen = {}
  256. # If the object has a member 'base', its value must name a complex type,
  257. # and there must be a discriminator.
  258. if base is not None:
  259. if discriminator is None:
  260. raise QAPIExprError(expr_info,
  261. "Union '%s' requires a discriminator to go "
  262. "along with base" %name)
  263. # If the union object has no member 'discriminator', it's a
  264. # simple union. If 'discriminator' is {}, it is an anonymous union.
  265. if discriminator is None or discriminator == {}:
  266. enum_define = None
  267. if base is not None:
  268. raise QAPIExprError(expr_info,
  269. "Union '%s' must not have a base"
  270. % name)
  271. # Else, it's a flat union.
  272. else:
  273. # The object must have a string member 'base'.
  274. if not isinstance(base, str):
  275. raise QAPIExprError(expr_info,
  276. "Flat union '%s' must have a string base field"
  277. % name)
  278. base_fields = find_base_fields(base)
  279. if not base_fields:
  280. raise QAPIExprError(expr_info,
  281. "Base '%s' is not a valid type"
  282. % base)
  283. # The value of member 'discriminator' must name a member of the
  284. # base type.
  285. if not isinstance(discriminator, str):
  286. raise QAPIExprError(expr_info,
  287. "Flat union '%s' discriminator must be a string"
  288. % name)
  289. discriminator_type = base_fields.get(discriminator)
  290. if not discriminator_type:
  291. raise QAPIExprError(expr_info,
  292. "Discriminator '%s' is not a member of base "
  293. "type '%s'"
  294. % (discriminator, base))
  295. enum_define = find_enum(discriminator_type)
  296. # Do not allow string discriminator
  297. if not enum_define:
  298. raise QAPIExprError(expr_info,
  299. "Discriminator '%s' must be of enumeration "
  300. "type" % discriminator)
  301. # Check every branch
  302. for (key, value) in members.items():
  303. # If the discriminator names an enum type, then all members
  304. # of 'data' must also be members of the enum type.
  305. if enum_define:
  306. if not key in enum_define['enum_values']:
  307. raise QAPIExprError(expr_info,
  308. "Discriminator value '%s' is not found in "
  309. "enum '%s'" %
  310. (key, enum_define["enum_name"]))
  311. # Otherwise, check for conflicts in the generated enum
  312. else:
  313. c_key = _generate_enum_string(key)
  314. if c_key in values:
  315. raise QAPIExprError(expr_info,
  316. "Union '%s' member '%s' clashes with '%s'"
  317. % (name, key, values[c_key]))
  318. values[c_key] = key
  319. # Ensure anonymous unions have no type conflicts.
  320. if discriminator == {}:
  321. if isinstance(value, list):
  322. raise QAPIExprError(expr_info,
  323. "Anonymous union '%s' member '%s' must "
  324. "not be array type" % (name, key))
  325. qtype = find_anonymous_member_qtype(value)
  326. if not qtype:
  327. raise QAPIExprError(expr_info,
  328. "Anonymous union '%s' member '%s' has "
  329. "invalid type '%s'" % (name, key, value))
  330. if qtype in types_seen:
  331. raise QAPIExprError(expr_info,
  332. "Anonymous union '%s' member '%s' can't "
  333. "be distinguished from member '%s'"
  334. % (name, key, types_seen[qtype]))
  335. types_seen[qtype] = key
  336. def check_enum(expr, expr_info):
  337. name = expr['enum']
  338. members = expr.get('data')
  339. values = { 'MAX': '(automatic)' }
  340. if not isinstance(members, list):
  341. raise QAPIExprError(expr_info,
  342. "Enum '%s' requires an array for 'data'" % name)
  343. for member in members:
  344. if not isinstance(member, str):
  345. raise QAPIExprError(expr_info,
  346. "Enum '%s' member '%s' is not a string"
  347. % (name, member))
  348. key = _generate_enum_string(member)
  349. if key in values:
  350. raise QAPIExprError(expr_info,
  351. "Enum '%s' member '%s' clashes with '%s'"
  352. % (name, member, values[key]))
  353. values[key] = member
  354. def check_exprs(schema):
  355. for expr_elem in schema.exprs:
  356. expr = expr_elem['expr']
  357. info = expr_elem['info']
  358. if expr.has_key('enum'):
  359. check_enum(expr, info)
  360. elif expr.has_key('union'):
  361. check_union(expr, info)
  362. elif expr.has_key('event'):
  363. check_event(expr, info)
  364. def parse_schema(input_file):
  365. try:
  366. schema = QAPISchema(open(input_file, "r"))
  367. except (QAPISchemaError, QAPIExprError), e:
  368. print >>sys.stderr, e
  369. exit(1)
  370. exprs = []
  371. for expr_elem in schema.exprs:
  372. expr = expr_elem['expr']
  373. if expr.has_key('enum'):
  374. add_enum(expr['enum'], expr.get('data'))
  375. elif expr.has_key('union'):
  376. add_union(expr)
  377. elif expr.has_key('type'):
  378. add_struct(expr)
  379. exprs.append(expr)
  380. # Try again for hidden UnionKind enum
  381. for expr_elem in schema.exprs:
  382. expr = expr_elem['expr']
  383. if expr.has_key('union'):
  384. if not discriminator_find_enum_define(expr):
  385. add_enum('%sKind' % expr['union'])
  386. try:
  387. check_exprs(schema)
  388. except QAPIExprError, e:
  389. print >>sys.stderr, e
  390. exit(1)
  391. return exprs
  392. def parse_args(typeinfo):
  393. if isinstance(typeinfo, str):
  394. struct = find_struct(typeinfo)
  395. assert struct != None
  396. typeinfo = struct['data']
  397. for member in typeinfo:
  398. argname = member
  399. argentry = typeinfo[member]
  400. optional = False
  401. structured = False
  402. if member.startswith('*'):
  403. argname = member[1:]
  404. optional = True
  405. if isinstance(argentry, OrderedDict):
  406. structured = True
  407. yield (argname, argentry, optional, structured)
  408. def de_camel_case(name):
  409. new_name = ''
  410. for ch in name:
  411. if ch.isupper() and new_name:
  412. new_name += '_'
  413. if ch == '-':
  414. new_name += '_'
  415. else:
  416. new_name += ch.lower()
  417. return new_name
  418. def camel_case(name):
  419. new_name = ''
  420. first = True
  421. for ch in name:
  422. if ch in ['_', '-']:
  423. first = True
  424. elif first:
  425. new_name += ch.upper()
  426. first = False
  427. else:
  428. new_name += ch.lower()
  429. return new_name
  430. def c_var(name, protect=True):
  431. # ANSI X3J11/88-090, 3.1.1
  432. c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
  433. 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
  434. 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
  435. 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
  436. 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
  437. # ISO/IEC 9899:1999, 6.4.1
  438. c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
  439. # ISO/IEC 9899:2011, 6.4.1
  440. c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
  441. '_Static_assert', '_Thread_local'])
  442. # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
  443. # excluding _.*
  444. gcc_words = set(['asm', 'typeof'])
  445. # C++ ISO/IEC 14882:2003 2.11
  446. cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
  447. 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
  448. 'namespace', 'new', 'operator', 'private', 'protected',
  449. 'public', 'reinterpret_cast', 'static_cast', 'template',
  450. 'this', 'throw', 'true', 'try', 'typeid', 'typename',
  451. 'using', 'virtual', 'wchar_t',
  452. # alternative representations
  453. 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
  454. 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
  455. # namespace pollution:
  456. polluted_words = set(['unix', 'errno'])
  457. if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
  458. return "q_" + name
  459. return name.replace('-', '_').lstrip("*")
  460. def c_fun(name, protect=True):
  461. return c_var(name, protect).replace('.', '_')
  462. def c_list_type(name):
  463. return '%sList' % name
  464. def type_name(name):
  465. if type(name) == list:
  466. return c_list_type(name[0])
  467. return name
  468. enum_types = []
  469. struct_types = []
  470. union_types = []
  471. def add_struct(definition):
  472. global struct_types
  473. struct_types.append(definition)
  474. def find_struct(name):
  475. global struct_types
  476. for struct in struct_types:
  477. if struct['type'] == name:
  478. return struct
  479. return None
  480. def add_union(definition):
  481. global union_types
  482. union_types.append(definition)
  483. def find_union(name):
  484. global union_types
  485. for union in union_types:
  486. if union['union'] == name:
  487. return union
  488. return None
  489. def add_enum(name, enum_values = None):
  490. global enum_types
  491. enum_types.append({"enum_name": name, "enum_values": enum_values})
  492. def find_enum(name):
  493. global enum_types
  494. for enum in enum_types:
  495. if enum['enum_name'] == name:
  496. return enum
  497. return None
  498. def is_enum(name):
  499. return find_enum(name) != None
  500. eatspace = '\033EATSPACE.'
  501. # A special suffix is added in c_type() for pointer types, and it's
  502. # stripped in mcgen(). So please notice this when you check the return
  503. # value of c_type() outside mcgen().
  504. def c_type(name, is_param=False):
  505. if name == 'str':
  506. if is_param:
  507. return 'const char *' + eatspace
  508. return 'char *' + eatspace
  509. elif name == 'int':
  510. return 'int64_t'
  511. elif (name == 'int8' or name == 'int16' or name == 'int32' or
  512. name == 'int64' or name == 'uint8' or name == 'uint16' or
  513. name == 'uint32' or name == 'uint64'):
  514. return name + '_t'
  515. elif name == 'size':
  516. return 'uint64_t'
  517. elif name == 'bool':
  518. return 'bool'
  519. elif name == 'number':
  520. return 'double'
  521. elif type(name) == list:
  522. return '%s *%s' % (c_list_type(name[0]), eatspace)
  523. elif is_enum(name):
  524. return name
  525. elif name == None or len(name) == 0:
  526. return 'void'
  527. elif name == name.upper():
  528. return '%sEvent *%s' % (camel_case(name), eatspace)
  529. else:
  530. return '%s *%s' % (name, eatspace)
  531. def is_c_ptr(name):
  532. suffix = "*" + eatspace
  533. return c_type(name).endswith(suffix)
  534. def genindent(count):
  535. ret = ""
  536. for i in range(count):
  537. ret += " "
  538. return ret
  539. indent_level = 0
  540. def push_indent(indent_amount=4):
  541. global indent_level
  542. indent_level += indent_amount
  543. def pop_indent(indent_amount=4):
  544. global indent_level
  545. indent_level -= indent_amount
  546. def cgen(code, **kwds):
  547. indent = genindent(indent_level)
  548. lines = code.split('\n')
  549. lines = map(lambda x: indent + x, lines)
  550. return '\n'.join(lines) % kwds + '\n'
  551. def mcgen(code, **kwds):
  552. raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
  553. return re.sub(re.escape(eatspace) + ' *', '', raw)
  554. def basename(filename):
  555. return filename.split("/")[-1]
  556. def guardname(filename):
  557. guard = basename(filename).rsplit(".", 1)[0]
  558. for substr in [".", " ", "-"]:
  559. guard = guard.replace(substr, "_")
  560. return guard.upper() + '_H'
  561. def guardstart(name):
  562. return mcgen('''
  563. #ifndef %(name)s
  564. #define %(name)s
  565. ''',
  566. name=guardname(name))
  567. def guardend(name):
  568. return mcgen('''
  569. #endif /* %(name)s */
  570. ''',
  571. name=guardname(name))
  572. # ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
  573. # ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
  574. # ENUM24_Name -> ENUM24_NAME
  575. def _generate_enum_string(value):
  576. c_fun_str = c_fun(value, False)
  577. if value.isupper():
  578. return c_fun_str
  579. new_name = ''
  580. l = len(c_fun_str)
  581. for i in range(l):
  582. c = c_fun_str[i]
  583. # When c is upper and no "_" appears before, do more checks
  584. if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
  585. # Case 1: next string is lower
  586. # Case 2: previous string is digit
  587. if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
  588. c_fun_str[i - 1].isdigit():
  589. new_name += '_'
  590. new_name += c
  591. return new_name.lstrip('_').upper()
  592. def generate_enum_full_value(enum_name, enum_value):
  593. abbrev_string = _generate_enum_string(enum_name)
  594. value_string = _generate_enum_string(enum_value)
  595. return "%s_%s" % (abbrev_string, value_string)