qapi.py 26 KB

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