annotate_ifdef_directives.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. #!/usr/bin/python
  2. # Copyright (c) 2017-2019, The Tor Project, Inc.
  3. # See LICENSE for licensing information
  4. r"""
  5. This script iterates over a list of C files. For each file, it looks at the
  6. #if/#else C macros, and annotates them with comments explaining what they
  7. match.
  8. For example, it replaces this kind of input...
  9. >>> INPUT = '''
  10. ... #ifdef HAVE_OCELOT
  11. ... C code here
  12. ... #if MIMSY == BOROGROVE
  13. ... block 1
  14. ... block 1
  15. ... block 1
  16. ... block 1
  17. ... #else
  18. ... block 2
  19. ... block 2
  20. ... block 2
  21. ... block 2
  22. ... #endif
  23. ... #endif
  24. ... '''
  25. With this kind of output:
  26. >>> EXPECTED_OUTPUT = '''
  27. ... #ifdef HAVE_OCELOT
  28. ... C code here
  29. ... #if MIMSY == BOROGROVE
  30. ... block 1
  31. ... block 1
  32. ... block 1
  33. ... block 1
  34. ... #else /* !(MIMSY == BOROGROVE) */
  35. ... block 2
  36. ... block 2
  37. ... block 2
  38. ... block 2
  39. ... #endif /* MIMSY == BOROGROVE */
  40. ... #endif /* defined(HAVE_OCELOT) */
  41. ... '''
  42. Here's how to use it:
  43. >>> import sys
  44. >>> if sys.version_info.major < 3: from cStringIO import StringIO
  45. >>> if sys.version_info.major >= 3: from io import StringIO
  46. >>> OUTPUT = StringIO()
  47. >>> translate(StringIO(INPUT), OUTPUT)
  48. >>> assert OUTPUT.getvalue() == EXPECTED_OUTPUT
  49. Note that only #else and #endif lines are annotated. Existing comments
  50. on those lines are removed.
  51. """
  52. import re
  53. # Any block with fewer than this many lines does not need annotations.
  54. LINE_OBVIOUSNESS_LIMIT = 4
  55. # Maximum line width. This includes a terminating newline character.
  56. #
  57. # (This is the maximum before encoding, so that if the the operating system
  58. # uses multiple characers to encode newline, that's still okay.)
  59. LINE_WIDTH=80
  60. class Problem(Exception):
  61. pass
  62. def close_parens_needed(expr):
  63. """Return the number of left-parentheses needed to make 'expr'
  64. balanced.
  65. >>> close_parens_needed("1+2")
  66. 0
  67. >>> close_parens_needed("(1 + 2)")
  68. 0
  69. >>> close_parens_needed("(1 + 2")
  70. 1
  71. >>> close_parens_needed("(1 + (2 *")
  72. 2
  73. >>> close_parens_needed("(1 + (2 * 3) + (4")
  74. 2
  75. """
  76. return expr.count("(") - expr.count(")")
  77. def truncate_expression(expr, new_width):
  78. """Given a parenthesized C expression in 'expr', try to return a new
  79. expression that is similar to 'expr', but no more than 'new_width'
  80. characters long.
  81. Try to return an expression with balanced parentheses.
  82. >>> truncate_expression("1+2+3", 8)
  83. '1+2+3'
  84. >>> truncate_expression("1+2+3+4+5", 8)
  85. '1+2+3...'
  86. >>> truncate_expression("(1+2+3+4)", 8)
  87. '(1+2...)'
  88. >>> truncate_expression("(1+(2+3+4))", 8)
  89. '(1+...)'
  90. >>> truncate_expression("(((((((((", 8)
  91. '((...))'
  92. """
  93. if len(expr) <= new_width:
  94. # The expression is already short enough.
  95. return expr
  96. ellipsis = "..."
  97. # Start this at the minimum that we might truncate.
  98. n_to_remove = len(expr) + len(ellipsis) - new_width
  99. # Try removing characters, one by one, until we get something where
  100. # re-balancing the parentheses still fits within the limit.
  101. while n_to_remove < len(expr):
  102. truncated = expr[:-n_to_remove] + ellipsis
  103. truncated += ")" * close_parens_needed(truncated)
  104. if len(truncated) <= new_width:
  105. return truncated
  106. n_to_remove += 1
  107. return ellipsis
  108. def commented_line(fmt, argument, maxwidth=LINE_WIDTH):
  109. # (This is a raw docstring so that our doctests can use \.)
  110. r"""
  111. Return fmt%argument, for use as a commented line. If the line would
  112. be longer than maxwidth, truncate argument but try to keep its
  113. parentheses balanced.
  114. Requires that fmt%"..." will fit into maxwidth characters.
  115. Requires that fmt ends with a newline.
  116. >>> commented_line("/* %s */\n", "hello world", 32)
  117. '/* hello world */\n'
  118. >>> commented_line("/* %s */\n", "hello world", 15)
  119. '/* hello... */\n'
  120. >>> commented_line("#endif /* %s */\n", "((1+2) && defined(FOO))", 32)
  121. '#endif /* ((1+2) && defi...) */\n'
  122. The default line limit is 80 characters including the newline:
  123. >>> long_argument = "long " * 100
  124. >>> long_line = commented_line("#endif /* %s */\n", long_argument)
  125. >>> len(long_line)
  126. 80
  127. >>> long_line[:40]
  128. '#endif /* long long long long long long '
  129. >>> long_line[40:]
  130. 'long long long long long long lon... */\n'
  131. If a line works out to being 80 characters naturally, it isn't truncated,
  132. and no ellipsis is added.
  133. >>> medium_argument = "a"*66
  134. >>> medium_line = commented_line("#endif /* %s */\n", medium_argument)
  135. >>> len(medium_line)
  136. 80
  137. >>> "..." in medium_line
  138. False
  139. >>> medium_line[:40]
  140. '#endif /* aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
  141. >>> medium_line[40:]
  142. 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa */\n'
  143. """
  144. assert fmt.endswith("\n")
  145. result = fmt % argument
  146. if len(result) <= maxwidth:
  147. return result
  148. else:
  149. # How long can we let the argument be? Try filling in the
  150. # format with an empty argument to find out.
  151. max_arg_width = maxwidth - len(fmt % "")
  152. result = fmt % truncate_expression(argument, max_arg_width)
  153. assert len(result) <= maxwidth
  154. return result
  155. def negate(expr):
  156. """Return a negated version of expr; try to avoid double-negation.
  157. We usually wrap expressions in parentheses and add a "!".
  158. >>> negate("A && B")
  159. '!(A && B)'
  160. But if we recognize the expression as negated, we can restore it.
  161. >>> negate(negate("A && B"))
  162. 'A && B'
  163. The same applies for defined(FOO).
  164. >>> negate("defined(FOO)")
  165. '!defined(FOO)'
  166. >>> negate(negate("defined(FOO)"))
  167. 'defined(FOO)'
  168. Internal parentheses don't confuse us:
  169. >>> negate("!(FOO) && !(BAR)")
  170. '!(!(FOO) && !(BAR))'
  171. """
  172. expr = expr.strip()
  173. # See whether we match !(...), with no intervening close-parens.
  174. m = re.match(r'^!\s*\(([^\)]*)\)$', expr)
  175. if m:
  176. return m.group(1)
  177. # See whether we match !?defined(...), with no intervening close-parens.
  178. m = re.match(r'^(!?)\s*(defined\([^\)]*\))$', expr)
  179. if m:
  180. if m.group(1) == "!":
  181. prefix = ""
  182. else:
  183. prefix = "!"
  184. return prefix + m.group(2)
  185. return "!(%s)" % expr
  186. def uncomment(s):
  187. """
  188. Remove existing trailing comments from an #else or #endif line.
  189. """
  190. s = re.sub(r'//.*','',s)
  191. s = re.sub(r'/\*.*','',s)
  192. return s.strip()
  193. def translate(f_in, f_out):
  194. """
  195. Read a file from f_in, and write its annotated version to f_out.
  196. """
  197. # A stack listing our current if/else state. Each member of the stack
  198. # is a list of directives. Each directive is a 3-tuple of
  199. # (command, rest, lineno)
  200. # where "command" is one of if/ifdef/ifndef/else/elif, and where
  201. # "rest" is an expression in a format suitable for use with #if, and where
  202. # lineno is the line number where the directive occurred.
  203. stack = []
  204. # the stack element corresponding to the top level of the file.
  205. whole_file = []
  206. cur_level = whole_file
  207. lineno = 0
  208. for line in f_in:
  209. lineno += 1
  210. m = re.match(r'\s*#\s*(if|ifdef|ifndef|else|endif|elif)\b\s*(.*)',
  211. line)
  212. if not m:
  213. # no directive, so we can just write it out.
  214. f_out.write(line)
  215. continue
  216. command,rest = m.groups()
  217. if command in ("if", "ifdef", "ifndef"):
  218. # The #if directive pushes us one level lower on the stack.
  219. if command == 'ifdef':
  220. rest = "defined(%s)"%uncomment(rest)
  221. elif command == 'ifndef':
  222. rest = "!defined(%s)"%uncomment(rest)
  223. elif rest.endswith("\\"):
  224. rest = rest[:-1]+"..."
  225. rest = uncomment(rest)
  226. new_level = [ (command, rest, lineno) ]
  227. stack.append(cur_level)
  228. cur_level = new_level
  229. f_out.write(line)
  230. elif command in ("else", "elif"):
  231. # We stay at the same level on the stack. If we have an #else,
  232. # we comment it.
  233. if len(cur_level) == 0 or cur_level[-1][0] == 'else':
  234. raise Problem("Unexpected #%s on %d"% (command,lineno))
  235. if (len(cur_level) == 1 and command == 'else' and
  236. lineno > cur_level[0][2] + LINE_OBVIOUSNESS_LIMIT):
  237. f_out.write(commented_line("#else /* %s */\n",
  238. negate(cur_level[0][1])))
  239. else:
  240. f_out.write(line)
  241. cur_level.append((command, rest, lineno))
  242. else:
  243. # We pop one element on the stack, and comment an endif.
  244. assert command == 'endif'
  245. if len(stack) == 0:
  246. raise Problem("Unmatched #%s on %s"% (command,lineno))
  247. if lineno <= cur_level[0][2] + LINE_OBVIOUSNESS_LIMIT:
  248. f_out.write(line)
  249. elif len(cur_level) == 1 or (
  250. len(cur_level) == 2 and cur_level[1][0] == 'else'):
  251. f_out.write(commented_line("#endif /* %s */\n",
  252. cur_level[0][1]))
  253. else:
  254. f_out.write(commented_line("#endif /* %s || ... */\n",
  255. cur_level[0][1]))
  256. cur_level = stack.pop()
  257. if len(stack) or cur_level != whole_file:
  258. raise Problem("Missing #endif")
  259. if __name__ == '__main__':
  260. import sys,os
  261. if sys.argv[1] == "--self-test":
  262. import doctest
  263. doctest.testmod()
  264. sys.exit(0)
  265. for fn in sys.argv[1:]:
  266. with open(fn+"_OUT", 'w') as output_file:
  267. translate(open(fn, 'r'), output_file)
  268. os.rename(fn+"_OUT", fn)