annotate_ifdef_directives 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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 uncomment(s):
  49. """
  50. Remove existing trailing comments from an #else or #endif line.
  51. """
  52. s = re.sub(r'//.*','',s)
  53. s = re.sub(r'/\*.*','',s)
  54. return s.strip()
  55. def translate(f_in, f_out):
  56. """
  57. Read a file from f_in, and write its annotated version to f_out.
  58. """
  59. # A stack listing our current if/else state. Each member of the stack
  60. # is a list of directives. Each directive is a 3-tuple of
  61. # (command, rest, lineno)
  62. # where "command" is one of if/ifdef/ifndef/else/elif, and where
  63. # "rest" is an expression in a format suitable for use with #if, and where
  64. # lineno is the line number where the directive occurred.
  65. stack = []
  66. # the stack element corresponding to the top level of the file.
  67. whole_file = []
  68. cur_level = whole_file
  69. lineno = 0
  70. for line in f_in:
  71. lineno += 1
  72. m = re.match(r'\s*#\s*(if|ifdef|ifndef|else|endif|elif)\b\s*(.*)',
  73. line)
  74. if not m:
  75. # no directive, so we can just write it out.
  76. f_out.write(line)
  77. continue
  78. command,rest = m.groups()
  79. if command in ("if", "ifdef", "ifndef"):
  80. # The #if directive pushes us one level lower on the stack.
  81. if command == 'ifdef':
  82. rest = "defined(%s)"%uncomment(rest)
  83. elif command == 'ifndef':
  84. rest = "!defined(%s)"%uncomment(rest)
  85. elif rest.endswith("\\"):
  86. rest = rest[:-1]+"..."
  87. rest = uncomment(rest)
  88. new_level = [ (command, rest, lineno) ]
  89. stack.append(cur_level)
  90. cur_level = new_level
  91. f_out.write(line)
  92. elif command in ("else", "elif"):
  93. # We stay at the same level on the stack. If we have an #else,
  94. # we comment it.
  95. if len(cur_level) == 0 or cur_level[-1][0] == 'else':
  96. raise Problem("Unexpected #%s on %d"% (command,lineno))
  97. if (len(cur_level) == 1 and command == 'else' and
  98. lineno > cur_level[0][2] + LINE_OBVIOUSNESS_LIMIT):
  99. f_out.write(commented_line("#else /* !(%s) */\n",
  100. cur_level[0][1]))
  101. else:
  102. f_out.write(line)
  103. cur_level.append((command, rest, lineno))
  104. else:
  105. # We pop one element on the stack, and comment an endif.
  106. assert command == 'endif'
  107. if len(stack) == 0:
  108. raise Problem("Unmatched #%s on %s"% (command,lineno))
  109. if lineno <= cur_level[0][2] + LINE_OBVIOUSNESS_LIMIT:
  110. f_out.write(line)
  111. elif len(cur_level) == 1 or (
  112. len(cur_level) == 2 and cur_level[1][0] == 'else'):
  113. f_out.write(commented_line("#endif /* %s */\n",
  114. cur_level[0][1]))
  115. else:
  116. f_out.write(commented_line("#endif /* %s || ... */\n",
  117. cur_level[0][1]))
  118. cur_level = stack.pop()
  119. if len(stack) or cur_level != whole_file:
  120. raise Problem("Missing #endif")
  121. import sys,os
  122. for fn in sys.argv[1:]:
  123. with open(fn+"_OUT", 'w') as output_file:
  124. translate(open(fn, 'r'), output_file)
  125. os.rename(fn+"_OUT", fn)