fixdiv.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #! /usr/bin/env python3
  2. """fixdiv - tool to fix division operators.
  3. To use this tool, first run `python -Qwarnall yourscript.py 2>warnings'.
  4. This runs the script `yourscript.py' while writing warning messages
  5. about all uses of the classic division operator to the file
  6. `warnings'. The warnings look like this:
  7. <file>:<line>: DeprecationWarning: classic <type> division
  8. The warnings are written to stderr, so you must use `2>' for the I/O
  9. redirect. I know of no way to redirect stderr on Windows in a DOS
  10. box, so you will have to modify the script to set sys.stderr to some
  11. kind of log file if you want to do this on Windows.
  12. The warnings are not limited to the script; modules imported by the
  13. script may also trigger warnings. In fact a useful technique is to
  14. write a test script specifically intended to exercise all code in a
  15. particular module or set of modules.
  16. Then run `python fixdiv.py warnings'. This first reads the warnings,
  17. looking for classic division warnings, and sorts them by file name and
  18. line number. Then, for each file that received at least one warning,
  19. it parses the file and tries to match the warnings up to the division
  20. operators found in the source code. If it is successful, it writes
  21. its findings to stdout, preceded by a line of dashes and a line of the
  22. form:
  23. Index: <file>
  24. If the only findings found are suggestions to change a / operator into
  25. a // operator, the output is acceptable input for the Unix 'patch'
  26. program.
  27. Here are the possible messages on stdout (N stands for a line number):
  28. - A plain-diff-style change ('NcN', a line marked by '<', a line
  29. containing '---', and a line marked by '>'):
  30. A / operator was found that should be changed to //. This is the
  31. recommendation when only int and/or long arguments were seen.
  32. - 'True division / operator at line N' and a line marked by '=':
  33. A / operator was found that can remain unchanged. This is the
  34. recommendation when only float and/or complex arguments were seen.
  35. - 'Ambiguous / operator (..., ...) at line N', line marked by '?':
  36. A / operator was found for which int or long as well as float or
  37. complex arguments were seen. This is highly unlikely; if it occurs,
  38. you may have to restructure the code to keep the classic semantics,
  39. or maybe you don't care about the classic semantics.
  40. - 'No conclusive evidence on line N', line marked by '*':
  41. A / operator was found for which no warnings were seen. This could
  42. be code that was never executed, or code that was only executed
  43. with user-defined objects as arguments. You will have to
  44. investigate further. Note that // can be overloaded separately from
  45. /, using __floordiv__. True division can also be separately
  46. overloaded, using __truediv__. Classic division should be the same
  47. as either of those. (XXX should I add a warning for division on
  48. user-defined objects, to disambiguate this case from code that was
  49. never executed?)
  50. - 'Phantom ... warnings for line N', line marked by '*':
  51. A warning was seen for a line not containing a / operator. The most
  52. likely cause is a warning about code executed by 'exec' or eval()
  53. (see note below), or an indirect invocation of the / operator, for
  54. example via the div() function in the operator module. It could
  55. also be caused by a change to the file between the time the test
  56. script was run to collect warnings and the time fixdiv was run.
  57. - 'More than one / operator in line N'; or
  58. 'More than one / operator per statement in lines N-N':
  59. The scanner found more than one / operator on a single line, or in a
  60. statement split across multiple lines. Because the warnings
  61. framework doesn't (and can't) show the offset within the line, and
  62. the code generator doesn't always give the correct line number for
  63. operations in a multi-line statement, we can't be sure whether all
  64. operators in the statement were executed. To be on the safe side,
  65. by default a warning is issued about this case. In practice, these
  66. cases are usually safe, and the -m option suppresses these warning.
  67. - 'Can't find the / operator in line N', line marked by '*':
  68. This really shouldn't happen. It means that the tokenize module
  69. reported a '/' operator but the line it returns didn't contain a '/'
  70. character at the indicated position.
  71. - 'Bad warning for line N: XYZ', line marked by '*':
  72. This really shouldn't happen. It means that a 'classic XYZ
  73. division' warning was read with XYZ being something other than
  74. 'int', 'long', 'float', or 'complex'.
  75. Notes:
  76. - The augmented assignment operator /= is handled the same way as the
  77. / operator.
  78. - This tool never looks at the // operator; no warnings are ever
  79. generated for use of this operator.
  80. - This tool never looks at the / operator when a future division
  81. statement is in effect; no warnings are generated in this case, and
  82. because the tool only looks at files for which at least one classic
  83. division warning was seen, it will never look at files containing a
  84. future division statement.
  85. - Warnings may be issued for code not read from a file, but executed
  86. using the exec() or eval() functions. These may have
  87. <string> in the filename position, in which case the fixdiv script
  88. will attempt and fail to open a file named '<string>' and issue a
  89. warning about this failure; or these may be reported as 'Phantom'
  90. warnings (see above). You're on your own to deal with these. You
  91. could make all recommended changes and add a future division
  92. statement to all affected files, and then re-run the test script; it
  93. should not issue any warnings. If there are any, and you have a
  94. hard time tracking down where they are generated, you can use the
  95. -Werror option to force an error instead of a first warning,
  96. generating a traceback.
  97. - The tool should be run from the same directory as that from which
  98. the original script was run, otherwise it won't be able to open
  99. files given by relative pathnames.
  100. """
  101. import sys
  102. import getopt
  103. import re
  104. import tokenize
  105. multi_ok = 0
  106. def main():
  107. try:
  108. opts, args = getopt.getopt(sys.argv[1:], "hm")
  109. except getopt.error as msg:
  110. usage(msg)
  111. return 2
  112. for o, a in opts:
  113. if o == "-h":
  114. print(__doc__)
  115. return
  116. if o == "-m":
  117. global multi_ok
  118. multi_ok = 1
  119. if not args:
  120. usage("at least one file argument is required")
  121. return 2
  122. if args[1:]:
  123. sys.stderr.write("%s: extra file arguments ignored\n", sys.argv[0])
  124. warnings = readwarnings(args[0])
  125. if warnings is None:
  126. return 1
  127. files = list(warnings.keys())
  128. if not files:
  129. print("No classic division warnings read from", args[0])
  130. return
  131. files.sort()
  132. exit = None
  133. for filename in files:
  134. x = process(filename, warnings[filename])
  135. exit = exit or x
  136. return exit
  137. def usage(msg):
  138. sys.stderr.write("%s: %s\n" % (sys.argv[0], msg))
  139. sys.stderr.write("Usage: %s [-m] warnings\n" % sys.argv[0])
  140. sys.stderr.write("Try `%s -h' for more information.\n" % sys.argv[0])
  141. PATTERN = (r"^(.+?):(\d+): DeprecationWarning: "
  142. r"classic (int|long|float|complex) division$")
  143. def readwarnings(warningsfile):
  144. prog = re.compile(PATTERN)
  145. try:
  146. f = open(warningsfile)
  147. except IOError as msg:
  148. sys.stderr.write("can't open: %s\n" % msg)
  149. return
  150. warnings = {}
  151. while 1:
  152. line = f.readline()
  153. if not line:
  154. break
  155. m = prog.match(line)
  156. if not m:
  157. if line.find("division") >= 0:
  158. sys.stderr.write("Warning: ignored input " + line)
  159. continue
  160. filename, lineno, what = m.groups()
  161. list = warnings.get(filename)
  162. if list is None:
  163. warnings[filename] = list = []
  164. list.append((int(lineno), sys.intern(what)))
  165. f.close()
  166. return warnings
  167. def process(filename, list):
  168. print("-"*70)
  169. assert list # if this fails, readwarnings() is broken
  170. try:
  171. fp = open(filename)
  172. except IOError as msg:
  173. sys.stderr.write("can't open: %s\n" % msg)
  174. return 1
  175. print("Index:", filename)
  176. f = FileContext(fp)
  177. list.sort()
  178. index = 0 # list[:index] has been processed, list[index:] is still to do
  179. g = tokenize.generate_tokens(f.readline)
  180. while 1:
  181. startlineno, endlineno, slashes = lineinfo = scanline(g)
  182. if startlineno is None:
  183. break
  184. assert startlineno <= endlineno is not None
  185. orphans = []
  186. while index < len(list) and list[index][0] < startlineno:
  187. orphans.append(list[index])
  188. index += 1
  189. if orphans:
  190. reportphantomwarnings(orphans, f)
  191. warnings = []
  192. while index < len(list) and list[index][0] <= endlineno:
  193. warnings.append(list[index])
  194. index += 1
  195. if not slashes and not warnings:
  196. pass
  197. elif slashes and not warnings:
  198. report(slashes, "No conclusive evidence")
  199. elif warnings and not slashes:
  200. reportphantomwarnings(warnings, f)
  201. else:
  202. if len(slashes) > 1:
  203. if not multi_ok:
  204. rows = []
  205. lastrow = None
  206. for (row, col), line in slashes:
  207. if row == lastrow:
  208. continue
  209. rows.append(row)
  210. lastrow = row
  211. assert rows
  212. if len(rows) == 1:
  213. print("*** More than one / operator in line", rows[0])
  214. else:
  215. print("*** More than one / operator per statement", end=' ')
  216. print("in lines %d-%d" % (rows[0], rows[-1]))
  217. intlong = []
  218. floatcomplex = []
  219. bad = []
  220. for lineno, what in warnings:
  221. if what in ("int", "long"):
  222. intlong.append(what)
  223. elif what in ("float", "complex"):
  224. floatcomplex.append(what)
  225. else:
  226. bad.append(what)
  227. lastrow = None
  228. for (row, col), line in slashes:
  229. if row == lastrow:
  230. continue
  231. lastrow = row
  232. line = chop(line)
  233. if line[col:col+1] != "/":
  234. print("*** Can't find the / operator in line %d:" % row)
  235. print("*", line)
  236. continue
  237. if bad:
  238. print("*** Bad warning for line %d:" % row, bad)
  239. print("*", line)
  240. elif intlong and not floatcomplex:
  241. print("%dc%d" % (row, row))
  242. print("<", line)
  243. print("---")
  244. print(">", line[:col] + "/" + line[col:])
  245. elif floatcomplex and not intlong:
  246. print("True division / operator at line %d:" % row)
  247. print("=", line)
  248. elif intlong and floatcomplex:
  249. print("*** Ambiguous / operator (%s, %s) at line %d:" % (
  250. "|".join(intlong), "|".join(floatcomplex), row))
  251. print("?", line)
  252. fp.close()
  253. def reportphantomwarnings(warnings, f):
  254. blocks = []
  255. lastrow = None
  256. lastblock = None
  257. for row, what in warnings:
  258. if row != lastrow:
  259. lastblock = [row]
  260. blocks.append(lastblock)
  261. lastblock.append(what)
  262. for block in blocks:
  263. row = block[0]
  264. whats = "/".join(block[1:])
  265. print("*** Phantom %s warnings for line %d:" % (whats, row))
  266. f.report(row, mark="*")
  267. def report(slashes, message):
  268. lastrow = None
  269. for (row, col), line in slashes:
  270. if row != lastrow:
  271. print("*** %s on line %d:" % (message, row))
  272. print("*", chop(line))
  273. lastrow = row
  274. class FileContext:
  275. def __init__(self, fp, window=5, lineno=1):
  276. self.fp = fp
  277. self.window = 5
  278. self.lineno = 1
  279. self.eoflookahead = 0
  280. self.lookahead = []
  281. self.buffer = []
  282. def fill(self):
  283. while len(self.lookahead) < self.window and not self.eoflookahead:
  284. line = self.fp.readline()
  285. if not line:
  286. self.eoflookahead = 1
  287. break
  288. self.lookahead.append(line)
  289. def readline(self):
  290. self.fill()
  291. if not self.lookahead:
  292. return ""
  293. line = self.lookahead.pop(0)
  294. self.buffer.append(line)
  295. self.lineno += 1
  296. return line
  297. def __getitem__(self, index):
  298. self.fill()
  299. bufstart = self.lineno - len(self.buffer)
  300. lookend = self.lineno + len(self.lookahead)
  301. if bufstart <= index < self.lineno:
  302. return self.buffer[index - bufstart]
  303. if self.lineno <= index < lookend:
  304. return self.lookahead[index - self.lineno]
  305. raise KeyError
  306. def report(self, first, last=None, mark="*"):
  307. if last is None:
  308. last = first
  309. for i in range(first, last+1):
  310. try:
  311. line = self[first]
  312. except KeyError:
  313. line = "<missing line>"
  314. print(mark, chop(line))
  315. def scanline(g):
  316. slashes = []
  317. startlineno = None
  318. endlineno = None
  319. for type, token, start, end, line in g:
  320. endlineno = end[0]
  321. if startlineno is None:
  322. startlineno = endlineno
  323. if token in ("/", "/="):
  324. slashes.append((start, line))
  325. if type == tokenize.NEWLINE:
  326. break
  327. return startlineno, endlineno, slashes
  328. def chop(line):
  329. if line.endswith("\n"):
  330. return line[:-1]
  331. else:
  332. return line
  333. if __name__ == "__main__":
  334. sys.exit(main())