annotate_ifdef_directives 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. #!/usr/bin/python
  2. # Copyright (c) 2017-2019, The Tor Project, Inc.
  3. # See LICENSE for licensing information
  4. # This script iterates over a list of C files. For each file, it looks at the
  5. # #if/#else C macros, and annotates them with comments explaining what they
  6. # match.
  7. #
  8. # For example, it replaces this:
  9. #
  10. # #ifdef HAVE_OCELOT
  11. # // 500 lines of ocelot code
  12. # #endif
  13. #
  14. # with this:
  15. #
  16. # #ifdef HAVE_OCELOT
  17. # // 500 lines of ocelot code
  18. # #endif /* defined(HAVE_OCELOT) */
  19. #
  20. # Note that only #else and #endif lines are annotated. Existing comments
  21. # on those lines are removed.
  22. import re
  23. # Any block with fewer than this many lines does not need annotations.
  24. LINE_OBVIOUSNESS_LIMIT = 4
  25. # Maximum line width. This includes a terminating newline character.
  26. #
  27. # (This is the maximum before encoding, so that if the the operating system
  28. # uses multiple characers to encode newline, that's still okay.)
  29. LINE_WIDTH=80
  30. class Problem(Exception):
  31. pass
  32. def commented_line(fmt, argument, maxwidth=LINE_WIDTH):
  33. """
  34. Return fmt%argument, for use as a commented line. If the line would
  35. be longer than maxwidth, truncate argument.
  36. Requires that fmt%"..." will fit into maxwidth characters.
  37. Requires that fmt ends with a newline.
  38. """
  39. assert fmt.endswith("\n")
  40. result = fmt % argument
  41. if len(result) <= maxwidth:
  42. return result
  43. else:
  44. # figure out how much we need to truncate by to fit the argument,
  45. # plus an ellipsis.
  46. ellipsis = "..."
  47. result = fmt % (argument + ellipsis)
  48. overrun = len(result) - maxwidth
  49. truncated_argument = argument[:-overrun] + ellipsis
  50. result = fmt % truncated_argument
  51. assert len(result) <= maxwidth
  52. return result
  53. def negate(expr):
  54. """Return a negated version of expr; try to avoid double-negation.
  55. We usually wrap expressions in parentheses and add a "!".
  56. >>> negate("A && B")
  57. '!(A && B)'
  58. But if we recognize the expression as negated, we can restore it.
  59. >>> negate(negate("A && B"))
  60. 'A && B'
  61. The same applies for defined(FOO).
  62. >>> negate("defined(FOO)")
  63. '!defined(FOO)'
  64. >>> negate(negate("defined(FOO)"))
  65. 'defined(FOO)'
  66. Internal parentheses don't confuse us:
  67. >>> negate("!(FOO) && !(BAR)")
  68. '!(!(FOO) && !(BAR))'
  69. """
  70. expr = expr.strip()
  71. # See whether we match !(...), with no intervening close-parens.
  72. m = re.match(r'^!\s*\(([^\)]*)\)$', expr)
  73. if m:
  74. return m.group(1)
  75. # See whether we match !?defined(...), with no intervening close-parens.
  76. m = re.match(r'^(!?)\s*(defined\([^\)]*\))$', expr)
  77. if m:
  78. if m.group(1) == "!":
  79. prefix = ""
  80. else:
  81. prefix = "!"
  82. return prefix + m.group(2)
  83. return "!(%s)" % expr
  84. def uncomment(s):
  85. """
  86. Remove existing trailing comments from an #else or #endif line.
  87. """
  88. s = re.sub(r'//.*','',s)
  89. s = re.sub(r'/\*.*','',s)
  90. return s.strip()
  91. def translate(f_in, f_out):
  92. """
  93. Read a file from f_in, and write its annotated version to f_out.
  94. """
  95. # A stack listing our current if/else state. Each member of the stack
  96. # is a list of directives. Each directive is a 3-tuple of
  97. # (command, rest, lineno)
  98. # where "command" is one of if/ifdef/ifndef/else/elif, and where
  99. # "rest" is an expression in a format suitable for use with #if, and where
  100. # lineno is the line number where the directive occurred.
  101. stack = []
  102. # the stack element corresponding to the top level of the file.
  103. whole_file = []
  104. cur_level = whole_file
  105. lineno = 0
  106. for line in f_in:
  107. lineno += 1
  108. m = re.match(r'\s*#\s*(if|ifdef|ifndef|else|endif|elif)\b\s*(.*)',
  109. line)
  110. if not m:
  111. # no directive, so we can just write it out.
  112. f_out.write(line)
  113. continue
  114. command,rest = m.groups()
  115. if command in ("if", "ifdef", "ifndef"):
  116. # The #if directive pushes us one level lower on the stack.
  117. if command == 'ifdef':
  118. rest = "defined(%s)"%uncomment(rest)
  119. elif command == 'ifndef':
  120. rest = "!defined(%s)"%uncomment(rest)
  121. elif rest.endswith("\\"):
  122. rest = rest[:-1]+"..."
  123. rest = uncomment(rest)
  124. new_level = [ (command, rest, lineno) ]
  125. stack.append(cur_level)
  126. cur_level = new_level
  127. f_out.write(line)
  128. elif command in ("else", "elif"):
  129. # We stay at the same level on the stack. If we have an #else,
  130. # we comment it.
  131. if len(cur_level) == 0 or cur_level[-1][0] == 'else':
  132. raise Problem("Unexpected #%s on %d"% (command,lineno))
  133. if (len(cur_level) == 1 and command == 'else' and
  134. lineno > cur_level[0][2] + LINE_OBVIOUSNESS_LIMIT):
  135. f_out.write(commented_line("#else /* %s */\n",
  136. negate(cur_level[0][1])))
  137. else:
  138. f_out.write(line)
  139. cur_level.append((command, rest, lineno))
  140. else:
  141. # We pop one element on the stack, and comment an endif.
  142. assert command == 'endif'
  143. if len(stack) == 0:
  144. raise Problem("Unmatched #%s on %s"% (command,lineno))
  145. if lineno <= cur_level[0][2] + LINE_OBVIOUSNESS_LIMIT:
  146. f_out.write(line)
  147. elif len(cur_level) == 1 or (
  148. len(cur_level) == 2 and cur_level[1][0] == 'else'):
  149. f_out.write(commented_line("#endif /* %s */\n",
  150. cur_level[0][1]))
  151. else:
  152. f_out.write(commented_line("#endif /* %s || ... */\n",
  153. cur_level[0][1]))
  154. cur_level = stack.pop()
  155. if len(stack) or cur_level != whole_file:
  156. raise Problem("Missing #endif")
  157. import sys,os
  158. for fn in sys.argv[1:]:
  159. with open(fn+"_OUT", 'w') as output_file:
  160. translate(open(fn, 'r'), output_file)
  161. os.rename(fn+"_OUT", fn)