_tokenize_py2.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. """Patched version of standard library tokenize, to deal with various bugs.
  2. Patches
  3. - Relevant parts of Gareth Rees' patch for Python issue #12691 (untokenizing),
  4. manually applied.
  5. - Newlines in comments and blank lines should be either NL or NEWLINE, depending
  6. on whether they are in a multi-line statement. Filed as Python issue #17061.
  7. -------------------------------------------------------------------------------
  8. Tokenization help for Python programs.
  9. generate_tokens(readline) is a generator that breaks a stream of
  10. text into Python tokens. It accepts a readline-like method which is called
  11. repeatedly to get the next line of input (or "" for EOF). It generates
  12. 5-tuples with these members:
  13. the token type (see token.py)
  14. the token (a string)
  15. the starting (row, column) indices of the token (a 2-tuple of ints)
  16. the ending (row, column) indices of the token (a 2-tuple of ints)
  17. the original line (string)
  18. It is designed to match the working of the Python tokenizer exactly, except
  19. that it produces COMMENT tokens for comments and gives type OP for all
  20. operators
  21. Older entry points
  22. tokenize_loop(readline, tokeneater)
  23. tokenize(readline, tokeneater=printtoken)
  24. are the same, except instead of generating tokens, tokeneater is a callback
  25. function to which the 5 fields described above are passed as 5 arguments,
  26. each time a new token is found."""
  27. from __future__ import print_function
  28. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  29. __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
  30. 'Skip Montanaro, Raymond Hettinger')
  31. import string, re
  32. from token import *
  33. import token
  34. __all__ = [x for x in dir(token) if not x.startswith("_")]
  35. __all__ += ["COMMENT", "tokenize", "generate_tokens", "NL", "untokenize"]
  36. del x
  37. del token
  38. __all__ += ["TokenError"]
  39. COMMENT = N_TOKENS
  40. tok_name[COMMENT] = 'COMMENT'
  41. NL = N_TOKENS + 1
  42. tok_name[NL] = 'NL'
  43. N_TOKENS += 2
  44. def group(*choices): return '(' + '|'.join(choices) + ')'
  45. def any(*choices): return group(*choices) + '*'
  46. def maybe(*choices): return group(*choices) + '?'
  47. Whitespace = r'[ \f\t]*'
  48. Comment = r'#[^\r\n]*'
  49. Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
  50. Name = r'[a-zA-Z_]\w*'
  51. Hexnumber = r'0[xX][\da-fA-F]+[lL]?'
  52. Octnumber = r'(0[oO][0-7]+)|(0[0-7]*)[lL]?'
  53. Binnumber = r'0[bB][01]+[lL]?'
  54. Decnumber = r'[1-9]\d*[lL]?'
  55. Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
  56. Exponent = r'[eE][-+]?\d+'
  57. Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent)
  58. Expfloat = r'\d+' + Exponent
  59. Floatnumber = group(Pointfloat, Expfloat)
  60. Imagnumber = group(r'\d+[jJ]', Floatnumber + r'[jJ]')
  61. Number = group(Imagnumber, Floatnumber, Intnumber)
  62. # Tail end of ' string.
  63. Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
  64. # Tail end of " string.
  65. Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
  66. # Tail end of ''' string.
  67. Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
  68. # Tail end of """ string.
  69. Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
  70. Triple = group("[uUbB]?[rR]?'''", '[uUbB]?[rR]?"""')
  71. # Single-line ' or " string.
  72. String = group(r"[uUbB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
  73. r'[uUbB]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
  74. # Because of leftmost-then-longest match semantics, be sure to put the
  75. # longest operators first (e.g., if = came before ==, == would get
  76. # recognized as two instances of =).
  77. Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=",
  78. r"//=?",
  79. r"[+\-*/%&|^=<>]=?",
  80. r"~")
  81. Bracket = '[][(){}]'
  82. Special = group(r'\r?\n', r'[:;.,`@]')
  83. Funny = group(Operator, Bracket, Special)
  84. PlainToken = group(Number, Funny, String, Name)
  85. Token = Ignore + PlainToken
  86. # First (or only) line of ' or " string.
  87. ContStr = group(r"[uUbB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
  88. group("'", r'\\\r?\n'),
  89. r'[uUbB]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
  90. group('"', r'\\\r?\n'))
  91. PseudoExtras = group(r'\\\r?\n', Comment, Triple)
  92. PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
  93. tokenprog, pseudoprog, single3prog, double3prog = map(
  94. re.compile, (Token, PseudoToken, Single3, Double3))
  95. endprogs = {"'": re.compile(Single), '"': re.compile(Double),
  96. "'''": single3prog, '"""': double3prog,
  97. "r'''": single3prog, 'r"""': double3prog,
  98. "u'''": single3prog, 'u"""': double3prog,
  99. "ur'''": single3prog, 'ur"""': double3prog,
  100. "R'''": single3prog, 'R"""': double3prog,
  101. "U'''": single3prog, 'U"""': double3prog,
  102. "uR'''": single3prog, 'uR"""': double3prog,
  103. "Ur'''": single3prog, 'Ur"""': double3prog,
  104. "UR'''": single3prog, 'UR"""': double3prog,
  105. "b'''": single3prog, 'b"""': double3prog,
  106. "br'''": single3prog, 'br"""': double3prog,
  107. "B'''": single3prog, 'B"""': double3prog,
  108. "bR'''": single3prog, 'bR"""': double3prog,
  109. "Br'''": single3prog, 'Br"""': double3prog,
  110. "BR'''": single3prog, 'BR"""': double3prog,
  111. 'r': None, 'R': None, 'u': None, 'U': None,
  112. 'b': None, 'B': None}
  113. triple_quoted = {}
  114. for t in ("'''", '"""',
  115. "r'''", 'r"""', "R'''", 'R"""',
  116. "u'''", 'u"""', "U'''", 'U"""',
  117. "ur'''", 'ur"""', "Ur'''", 'Ur"""',
  118. "uR'''", 'uR"""', "UR'''", 'UR"""',
  119. "b'''", 'b"""', "B'''", 'B"""',
  120. "br'''", 'br"""', "Br'''", 'Br"""',
  121. "bR'''", 'bR"""', "BR'''", 'BR"""'):
  122. triple_quoted[t] = t
  123. single_quoted = {}
  124. for t in ("'", '"',
  125. "r'", 'r"', "R'", 'R"',
  126. "u'", 'u"', "U'", 'U"',
  127. "ur'", 'ur"', "Ur'", 'Ur"',
  128. "uR'", 'uR"', "UR'", 'UR"',
  129. "b'", 'b"', "B'", 'B"',
  130. "br'", 'br"', "Br'", 'Br"',
  131. "bR'", 'bR"', "BR'", 'BR"' ):
  132. single_quoted[t] = t
  133. tabsize = 8
  134. class TokenError(Exception): pass
  135. class StopTokenizing(Exception): pass
  136. def printtoken(type, token, srow_scol, erow_ecol, line): # for testing
  137. srow, scol = srow_scol
  138. erow, ecol = erow_ecol
  139. print("%d,%d-%d,%d:\t%s\t%s" % \
  140. (srow, scol, erow, ecol, tok_name[type], repr(token)))
  141. def tokenize(readline, tokeneater=printtoken):
  142. """
  143. The tokenize() function accepts two parameters: one representing the
  144. input stream, and one providing an output mechanism for tokenize().
  145. The first parameter, readline, must be a callable object which provides
  146. the same interface as the readline() method of built-in file objects.
  147. Each call to the function should return one line of input as a string.
  148. The second parameter, tokeneater, must also be a callable object. It is
  149. called once for each token, with five arguments, corresponding to the
  150. tuples generated by generate_tokens().
  151. """
  152. try:
  153. tokenize_loop(readline, tokeneater)
  154. except StopTokenizing:
  155. pass
  156. # backwards compatible interface
  157. def tokenize_loop(readline, tokeneater):
  158. for token_info in generate_tokens(readline):
  159. tokeneater(*token_info)
  160. class Untokenizer:
  161. def __init__(self):
  162. self.tokens = []
  163. self.prev_row = 1
  164. self.prev_col = 0
  165. def add_whitespace(self, start):
  166. row, col = start
  167. assert row >= self.prev_row
  168. col_offset = col - self.prev_col
  169. if col_offset > 0:
  170. self.tokens.append(" " * col_offset)
  171. elif row > self.prev_row and tok_type not in (NEWLINE, NL, ENDMARKER):
  172. # Line was backslash-continued
  173. self.tokens.append(" ")
  174. def untokenize(self, tokens):
  175. iterable = iter(tokens)
  176. for t in iterable:
  177. if len(t) == 2:
  178. self.compat(t, iterable)
  179. break
  180. tok_type, token, start, end = t[:4]
  181. self.add_whitespace(start)
  182. self.tokens.append(token)
  183. self.prev_row, self.prev_col = end
  184. if tok_type in (NEWLINE, NL):
  185. self.prev_row += 1
  186. self.prev_col = 0
  187. return "".join(self.tokens)
  188. def compat(self, token, iterable):
  189. # This import is here to avoid problems when the itertools
  190. # module is not built yet and tokenize is imported.
  191. from itertools import chain
  192. startline = False
  193. prevstring = False
  194. indents = []
  195. toks_append = self.tokens.append
  196. for tok in chain([token], iterable):
  197. toknum, tokval = tok[:2]
  198. if toknum in (NAME, NUMBER):
  199. tokval += ' '
  200. # Insert a space between two consecutive strings
  201. if toknum == STRING:
  202. if prevstring:
  203. tokval = ' ' + tokval
  204. prevstring = True
  205. else:
  206. prevstring = False
  207. if toknum == INDENT:
  208. indents.append(tokval)
  209. continue
  210. elif toknum == DEDENT:
  211. indents.pop()
  212. continue
  213. elif toknum in (NEWLINE, NL):
  214. startline = True
  215. elif startline and indents:
  216. toks_append(indents[-1])
  217. startline = False
  218. toks_append(tokval)
  219. def untokenize(iterable):
  220. """Transform tokens back into Python source code.
  221. Each element returned by the iterable must be a token sequence
  222. with at least two elements, a token number and token value. If
  223. only two tokens are passed, the resulting output is poor.
  224. Round-trip invariant for full input:
  225. Untokenized source will match input source exactly
  226. Round-trip invariant for limited intput:
  227. # Output text will tokenize the back to the input
  228. t1 = [tok[:2] for tok in generate_tokens(f.readline)]
  229. newcode = untokenize(t1)
  230. readline = iter(newcode.splitlines(1)).next
  231. t2 = [tok[:2] for tok in generate_tokens(readline)]
  232. assert t1 == t2
  233. """
  234. ut = Untokenizer()
  235. return ut.untokenize(iterable)
  236. def generate_tokens(readline):
  237. """
  238. The generate_tokens() generator requires one argment, readline, which
  239. must be a callable object which provides the same interface as the
  240. readline() method of built-in file objects. Each call to the function
  241. should return one line of input as a string. Alternately, readline
  242. can be a callable function terminating with StopIteration:
  243. readline = open(myfile).next # Example of alternate readline
  244. The generator produces 5-tuples with these members: the token type; the
  245. token string; a 2-tuple (srow, scol) of ints specifying the row and
  246. column where the token begins in the source; a 2-tuple (erow, ecol) of
  247. ints specifying the row and column where the token ends in the source;
  248. and the line on which the token was found. The line passed is the
  249. logical line; continuation lines are included.
  250. """
  251. lnum = parenlev = continued = 0
  252. namechars, numchars = string.ascii_letters + '_', '0123456789'
  253. contstr, needcont = '', 0
  254. contline = None
  255. indents = [0]
  256. while 1: # loop over lines in stream
  257. try:
  258. line = readline()
  259. except StopIteration:
  260. line = ''
  261. lnum += 1
  262. pos, max = 0, len(line)
  263. if contstr: # continued string
  264. if not line:
  265. raise TokenError("EOF in multi-line string", strstart)
  266. endmatch = endprog.match(line)
  267. if endmatch:
  268. pos = end = endmatch.end(0)
  269. yield (STRING, contstr + line[:end],
  270. strstart, (lnum, end), contline + line)
  271. contstr, needcont = '', 0
  272. contline = None
  273. elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
  274. yield (ERRORTOKEN, contstr + line,
  275. strstart, (lnum, len(line)), contline)
  276. contstr = ''
  277. contline = None
  278. continue
  279. else:
  280. contstr = contstr + line
  281. contline = contline + line
  282. continue
  283. elif parenlev == 0 and not continued: # new statement
  284. if not line: break
  285. column = 0
  286. while pos < max: # measure leading whitespace
  287. if line[pos] == ' ':
  288. column += 1
  289. elif line[pos] == '\t':
  290. column = (column//tabsize + 1)*tabsize
  291. elif line[pos] == '\f':
  292. column = 0
  293. else:
  294. break
  295. pos += 1
  296. if pos == max:
  297. break
  298. if line[pos] in '#\r\n': # skip comments or blank lines
  299. if line[pos] == '#':
  300. comment_token = line[pos:].rstrip('\r\n')
  301. nl_pos = pos + len(comment_token)
  302. yield (COMMENT, comment_token,
  303. (lnum, pos), (lnum, pos + len(comment_token)), line)
  304. yield (NEWLINE, line[nl_pos:],
  305. (lnum, nl_pos), (lnum, len(line)), line)
  306. else:
  307. yield (NEWLINE, line[pos:],
  308. (lnum, pos), (lnum, len(line)), line)
  309. continue
  310. if column > indents[-1]: # count indents or dedents
  311. indents.append(column)
  312. yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
  313. while column < indents[-1]:
  314. if column not in indents:
  315. raise IndentationError(
  316. "unindent does not match any outer indentation level",
  317. ("<tokenize>", lnum, pos, line))
  318. indents = indents[:-1]
  319. yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
  320. else: # continued statement
  321. if not line:
  322. raise TokenError("EOF in multi-line statement", (lnum, 0))
  323. continued = 0
  324. while pos < max:
  325. pseudomatch = pseudoprog.match(line, pos)
  326. if pseudomatch: # scan for tokens
  327. start, end = pseudomatch.span(1)
  328. spos, epos, pos = (lnum, start), (lnum, end), end
  329. token, initial = line[start:end], line[start]
  330. if initial in numchars or \
  331. (initial == '.' and token != '.'): # ordinary number
  332. yield (NUMBER, token, spos, epos, line)
  333. elif initial in '\r\n':
  334. yield (NL if parenlev > 0 else NEWLINE,
  335. token, spos, epos, line)
  336. elif initial == '#':
  337. assert not token.endswith("\n")
  338. yield (COMMENT, token, spos, epos, line)
  339. elif token in triple_quoted:
  340. endprog = endprogs[token]
  341. endmatch = endprog.match(line, pos)
  342. if endmatch: # all on one line
  343. pos = endmatch.end(0)
  344. token = line[start:pos]
  345. yield (STRING, token, spos, (lnum, pos), line)
  346. else:
  347. strstart = (lnum, start) # multiple lines
  348. contstr = line[start:]
  349. contline = line
  350. break
  351. elif initial in single_quoted or \
  352. token[:2] in single_quoted or \
  353. token[:3] in single_quoted:
  354. if token[-1] == '\n': # continued string
  355. strstart = (lnum, start)
  356. endprog = (endprogs[initial] or endprogs[token[1]] or
  357. endprogs[token[2]])
  358. contstr, needcont = line[start:], 1
  359. contline = line
  360. break
  361. else: # ordinary string
  362. yield (STRING, token, spos, epos, line)
  363. elif initial in namechars: # ordinary name
  364. yield (NAME, token, spos, epos, line)
  365. elif initial == '\\': # continued stmt
  366. continued = 1
  367. else:
  368. if initial in '([{':
  369. parenlev += 1
  370. elif initial in ')]}':
  371. parenlev -= 1
  372. yield (OP, token, spos, epos, line)
  373. else:
  374. yield (ERRORTOKEN, line[pos],
  375. (lnum, pos), (lnum, pos+1), line)
  376. pos += 1
  377. for indent in indents[1:]: # pop remaining indent levels
  378. yield (DEDENT, '', (lnum, 0), (lnum, 0), '')
  379. yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '')
  380. if __name__ == '__main__': # testing
  381. import sys
  382. if len(sys.argv) > 1:
  383. tokenize(open(sys.argv[1]).readline)
  384. else:
  385. tokenize(sys.stdin.readline)