explode_asserts.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. #!/usr/bin/env python3
  2. import parsy as p
  3. import re
  4. import io
  5. import sys
  6. ASSERT_PATTERN = p.string('LFS_ASSERT') | p.string('assert')
  7. ASSERT_CHARS = 'La'
  8. ASSERT_TARGET = '__LFS_ASSERT_{TYPE}_{COMP}'
  9. ASSERT_TESTS = {
  10. 'int': """
  11. __typeof__({lh}) _lh = {lh};
  12. __typeof__({lh}) _rh = (__typeof__({lh})){rh};
  13. if (!(_lh {op} _rh)) {{
  14. printf("%s:%d:assert: "
  15. "assert failed with %"PRIiMAX", expected {comp} %"PRIiMAX"\\n",
  16. {file}, {line}, (intmax_t)_lh, (intmax_t)_rh);
  17. exit(-2);
  18. }}
  19. """,
  20. 'str': """
  21. const char *_lh = {lh};
  22. const char *_rh = {rh};
  23. if (!(strcmp(_lh, _rh) {op} 0)) {{
  24. printf("%s:%d:assert: "
  25. "assert failed with \\\"%s\\\", expected {comp} \\\"%s\\\"\\n",
  26. {file}, {line}, _lh, _rh);
  27. exit(-2);
  28. }}
  29. """,
  30. 'bool': """
  31. bool _lh = !!({lh});
  32. bool _rh = !!({rh});
  33. if (!(_lh {op} _rh)) {{
  34. printf("%s:%d:assert: "
  35. "assert failed with %s, expected {comp} %s\\n",
  36. {file}, {line}, _lh ? "true" : "false", _rh ? "true" : "false");
  37. exit(-2);
  38. }}
  39. """,
  40. }
  41. def mkassert(lh, rh='true', type='bool', comp='eq'):
  42. return ((ASSERT_TARGET + "({lh}, {rh}, __FILE__, __LINE__, __func__)")
  43. .format(
  44. type=type, TYPE=type.upper(),
  45. comp=comp, COMP=comp.upper(),
  46. lh=lh.strip(' '),
  47. rh=rh.strip(' ')))
  48. def mkdecl(type, comp, op):
  49. return ((
  50. "#define "+ASSERT_TARGET+"(lh, rh, file, line, func)"
  51. " do {{"+re.sub('\s+', ' ', ASSERT_TESTS[type])+"}} while (0)\n")
  52. .format(
  53. type=type, TYPE=type.upper(),
  54. comp=comp, COMP=comp.upper(),
  55. lh='lh', rh='rh', op=op,
  56. file='file', line='line', func='func'))
  57. # add custom until combinator
  58. def until(self, end):
  59. return end.should_fail('should fail').then(self).many()
  60. p.Parser.until = until
  61. pcomp = (
  62. p.string('==').tag('eq') |
  63. p.string('!=').tag('ne') |
  64. p.string('<=').tag('le') |
  65. p.string('>=').tag('ge') |
  66. p.string('<').tag('lt') |
  67. p.string('>').tag('gt'));
  68. plogic = p.string('&&') | p.string('||')
  69. @p.generate
  70. def pstrassert():
  71. yield ASSERT_PATTERN + p.regex('\s*') + p.string('(') + p.regex('\s*')
  72. yield p.string('strcmp') + p.regex('\s*') + p.string('(') + p.regex('\s*')
  73. lh = yield pexpr.until(p.string(',') | p.string(')') | plogic)
  74. yield p.string(',') + p.regex('\s*')
  75. rh = yield pexpr.until(p.string(')') | plogic)
  76. yield p.string(')') + p.regex('\s*')
  77. op = yield pcomp
  78. yield p.regex('\s*') + p.string('0') + p.regex('\s*') + p.string(')')
  79. return mkassert(''.join(lh), ''.join(rh), 'str', op[0])
  80. @p.generate
  81. def pintassert():
  82. yield ASSERT_PATTERN + p.regex('\s*') + p.string('(') + p.regex('\s*')
  83. lh = yield pexpr.until(pcomp | p.string(')') | plogic)
  84. op = yield pcomp
  85. rh = yield pexpr.until(p.string(')') | plogic)
  86. yield p.string(')')
  87. return mkassert(''.join(lh), ''.join(rh), 'int', op[0])
  88. @p.generate
  89. def pboolassert():
  90. yield ASSERT_PATTERN + p.regex('\s*') + p.string('(') + p.regex('\s*')
  91. expr = yield pexpr.until(p.string(')'))
  92. yield p.string(')')
  93. return mkassert(''.join(expr), 'true', 'bool', 'eq')
  94. passert = p.peek(ASSERT_PATTERN) >> (pstrassert | pintassert | pboolassert)
  95. @p.generate
  96. def pcomment1():
  97. yield p.string('//')
  98. s = yield p.regex('[^\\n]*')
  99. yield p.string('\n')
  100. return '//' + s + '\n'
  101. @p.generate
  102. def pcomment2():
  103. yield p.string('/*')
  104. s = yield p.regex('((?!\*/).)*')
  105. yield p.string('*/')
  106. return '/*' + ''.join(s) + '*/'
  107. @p.generate
  108. def pcomment3():
  109. yield p.string('#')
  110. s = yield p.regex('[^\\n]*')
  111. yield p.string('\n')
  112. return '#' + s + '\n'
  113. pws = p.regex('\s+') | pcomment1 | pcomment2 | pcomment3
  114. @p.generate
  115. def pstring():
  116. q = yield p.regex('["\']')
  117. s = yield (p.string('\\%s' % q) | p.regex('[^%s]' % q)).many()
  118. yield p.string(q)
  119. return q + ''.join(s) + q
  120. @p.generate
  121. def pnested():
  122. l = yield p.string('(')
  123. n = yield pexpr.until(p.string(')'))
  124. r = yield p.string(')')
  125. return l + ''.join(n) + r
  126. pexpr = (
  127. # shortcut for a bit better performance
  128. p.regex('[^%s/#\'"();{}=><,&|-]+' % ASSERT_CHARS) |
  129. pws |
  130. passert |
  131. pstring |
  132. pnested |
  133. p.string('->') |
  134. p.regex('.', re.DOTALL))
  135. @p.generate
  136. def pstmt():
  137. ws = yield pws.many()
  138. lh = yield pexpr.until(p.string('=>') | p.regex('[;{}]'))
  139. op = yield p.string('=>').optional()
  140. if op == '=>':
  141. rh = yield pstmt
  142. return ''.join(ws) + mkassert(''.join(lh), rh, 'int', 'eq')
  143. else:
  144. return ''.join(ws) + ''.join(lh)
  145. @p.generate
  146. def pstmts():
  147. a = yield pstmt
  148. b = yield (p.regex('[;{}]') + pstmt).many()
  149. return [a] + b
  150. def main(args):
  151. inf = open(args.input, 'r') if args.input else sys.stdin
  152. outf = open(args.output, 'w') if args.output else sys.stdout
  153. # parse C code
  154. input = inf.read()
  155. stmts = pstmts.parse(input)
  156. # write extra verbose asserts
  157. outf.write("#include <stdbool.h>\n")
  158. outf.write("#include <stdint.h>\n")
  159. outf.write("#include <inttypes.h>\n")
  160. outf.write(mkdecl('int', 'eq', '=='))
  161. outf.write(mkdecl('int', 'ne', '!='))
  162. outf.write(mkdecl('int', 'lt', '<'))
  163. outf.write(mkdecl('int', 'gt', '>'))
  164. outf.write(mkdecl('int', 'le', '<='))
  165. outf.write(mkdecl('int', 'ge', '>='))
  166. outf.write(mkdecl('str', 'eq', '=='))
  167. outf.write(mkdecl('str', 'ne', '!='))
  168. outf.write(mkdecl('str', 'lt', '<'))
  169. outf.write(mkdecl('str', 'gt', '>'))
  170. outf.write(mkdecl('str', 'le', '<='))
  171. outf.write(mkdecl('str', 'ge', '>='))
  172. outf.write(mkdecl('bool', 'eq', '=='))
  173. if args.input:
  174. outf.write("#line %d \"%s\"\n" % (1, args.input))
  175. # write parsed statements
  176. for stmt in stmts:
  177. outf.write(stmt)
  178. if __name__ == "__main__":
  179. import argparse
  180. parser = argparse.ArgumentParser(
  181. description="Cpp step that increases assert verbosity")
  182. parser.add_argument('input', nargs='?',
  183. help="Input C file after cpp.")
  184. parser.add_argument('-o', '--output',
  185. help="Output C file.")
  186. main(parser.parse_args())