annotate_ifdef_directives 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  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.
  26. LINE_WIDTH=80
  27. class Problem(Exception):
  28. pass
  29. def commented_line(fmt, argument, maxwidth=LINE_WIDTH):
  30. """
  31. Return fmt%argument, for use as a commented line. If the line would
  32. be longer than maxwidth, truncate argument.
  33. Requires that fmt%"..." will fit into maxwidth characters.
  34. """
  35. result = fmt % argument
  36. if len(result) <= maxwidth:
  37. return result
  38. else:
  39. # figure out how much we need to truncate by to fit the argument,
  40. # plus an ellipsis.
  41. ellipsis = "..."
  42. result = fmt % (argument + ellipsis)
  43. overrun = len(result) - maxwidth
  44. truncated_argument = argument[:-overrun] + ellipsis
  45. result = fmt % truncated_argument
  46. assert len(result) <= maxwidth
  47. return result
  48. def negate(expr):
  49. """Return a negated version of expr; try to avoid double-negation.
  50. We usually wrap expressions in parentheses and add a "!".
  51. >>> negate("A && B")
  52. '!(A && B)'
  53. But if we recognize the expression as negated, we can restore it.
  54. >>> negate(negate("A && B"))
  55. 'A && B'
  56. The same applies for defined(FOO).
  57. >>> negate("defined(FOO)")
  58. '!defined(FOO)'
  59. >>> negate(negate("defined(FOO)"))
  60. 'defined(FOO)'
  61. Internal parentheses don't confuse us:
  62. >>> negate("!(FOO) && !(BAR)")
  63. '!(!(FOO) && !(BAR))'
  64. """
  65. expr = expr.strip()
  66. # See whether we match !(...), with no intervening close-parens.
  67. m = re.match(r'^!\s*\(([^\)]*)\)$', expr)
  68. if m:
  69. return m.group(1)
  70. # See whether we match !?defined(...), with no intervening close-parens.
  71. m = re.match(r'^(!?)\s*(defined\([^\)]*\))$', expr)
  72. if m:
  73. if m.group(1) == "!":
  74. prefix = ""
  75. else:
  76. prefix = "!"
  77. return prefix + m.group(2)
  78. return "!(%s)" % expr
  79. def uncomment(s):
  80. """
  81. Remove existing trailing comments from an #else or #endif line.
  82. """
  83. s = re.sub(r'//.*','',s)
  84. s = re.sub(r'/\*.*','',s)
  85. return s.strip()
  86. def translate(f_in, f_out):
  87. """
  88. Read a file from f_in, and write its annotated version to f_out.
  89. """
  90. # A stack listing our current if/else state. Each member of the stack
  91. # is a list of directives. Each directive is a 3-tuple of
  92. # (command, rest, lineno)
  93. # where "command" is one of if/ifdef/ifndef/else/elif, and where
  94. # "rest" is an expression in a format suitable for use with #if, and where
  95. # lineno is the line number where the directive occurred.
  96. stack = []
  97. # the stack element corresponding to the top level of the file.
  98. whole_file = []
  99. cur_level = whole_file
  100. lineno = 0
  101. for line in f_in:
  102. lineno += 1
  103. m = re.match(r'\s*#\s*(if|ifdef|ifndef|else|endif|elif)\b\s*(.*)',
  104. line)
  105. if not m:
  106. # no directive, so we can just write it out.
  107. f_out.write(line)
  108. continue
  109. command,rest = m.groups()
  110. if command in ("if", "ifdef", "ifndef"):
  111. # The #if directive pushes us one level lower on the stack.
  112. if command == 'ifdef':
  113. rest = "defined(%s)"%uncomment(rest)
  114. elif command == 'ifndef':
  115. rest = "!defined(%s)"%uncomment(rest)
  116. elif rest.endswith("\\"):
  117. rest = rest[:-1]+"..."
  118. rest = uncomment(rest)
  119. new_level = [ (command, rest, lineno) ]
  120. stack.append(cur_level)
  121. cur_level = new_level
  122. f_out.write(line)
  123. elif command in ("else", "elif"):
  124. # We stay at the same level on the stack. If we have an #else,
  125. # we comment it.
  126. if len(cur_level) == 0 or cur_level[-1][0] == 'else':
  127. raise Problem("Unexpected #%s on %d"% (command,lineno))
  128. if (len(cur_level) == 1 and command == 'else' and
  129. lineno > cur_level[0][2] + LINE_OBVIOUSNESS_LIMIT):
  130. f_out.write(commented_line("#else /* %s */\n",
  131. negate(cur_level[0][1])))
  132. else:
  133. f_out.write(line)
  134. cur_level.append((command, rest, lineno))
  135. else:
  136. # We pop one element on the stack, and comment an endif.
  137. assert command == 'endif'
  138. if len(stack) == 0:
  139. raise Problem("Unmatched #%s on %s"% (command,lineno))
  140. if lineno <= cur_level[0][2] + LINE_OBVIOUSNESS_LIMIT:
  141. f_out.write(line)
  142. elif len(cur_level) == 1 or (
  143. len(cur_level) == 2 and cur_level[1][0] == 'else'):
  144. f_out.write(commented_line("#endif /* %s */\n",
  145. cur_level[0][1]))
  146. else:
  147. f_out.write(commented_line("#endif /* %s || ... */\n",
  148. cur_level[0][1]))
  149. cur_level = stack.pop()
  150. if len(stack) or cur_level != whole_file:
  151. raise Problem("Missing #endif")
  152. import sys,os
  153. for fn in sys.argv[1:]:
  154. with open(fn+"_OUT", 'w') as output_file:
  155. translate(open(fn, 'r'), output_file)
  156. os.rename(fn+"_OUT", fn)