qapi.py 19 KB

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