tokenize.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. """Tokenization help for Python programs.
  2. tokenize(readline) is a generator that breaks a stream of bytes into
  3. Python tokens. It decodes the bytes according to PEP-0263 for
  4. determining source file encoding.
  5. It accepts a readline-like method which is called repeatedly to get the
  6. next line of input (or b"" for EOF). It generates 5-tuples with these
  7. members:
  8. the token type (see token.py)
  9. the token (a string)
  10. the starting (row, column) indices of the token (a 2-tuple of ints)
  11. the ending (row, column) indices of the token (a 2-tuple of ints)
  12. the original line (string)
  13. It is designed to match the working of the Python tokenizer exactly, except
  14. that it produces COMMENT tokens for comments and gives type OP for all
  15. operators. Additionally, all token lists start with an ENCODING token
  16. which tells you which encoding was used to decode the bytes stream.
  17. """
  18. __author__ = 'Ka-Ping Yee <ping@lfw.org>'
  19. __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
  20. 'Skip Montanaro, Raymond Hettinger, Trent Nelson, '
  21. 'Michael Foord')
  22. from builtins import open as _builtin_open
  23. from codecs import lookup, BOM_UTF8
  24. import collections
  25. import functools
  26. from io import TextIOWrapper
  27. import itertools as _itertools
  28. import re
  29. import sys
  30. from token import *
  31. from token import EXACT_TOKEN_TYPES
  32. import _tokenize
  33. cookie_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII)
  34. blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII)
  35. import token
  36. __all__ = token.__all__ + ["tokenize", "generate_tokens", "detect_encoding",
  37. "untokenize", "TokenInfo"]
  38. del token
  39. class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
  40. def __repr__(self):
  41. annotated_type = '%d (%s)' % (self.type, tok_name[self.type])
  42. return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' %
  43. self._replace(type=annotated_type))
  44. @property
  45. def exact_type(self):
  46. if self.type == OP and self.string in EXACT_TOKEN_TYPES:
  47. return EXACT_TOKEN_TYPES[self.string]
  48. else:
  49. return self.type
  50. def group(*choices): return '(' + '|'.join(choices) + ')'
  51. def any(*choices): return group(*choices) + '*'
  52. def maybe(*choices): return group(*choices) + '?'
  53. # Note: we use unicode matching for names ("\w") but ascii matching for
  54. # number literals.
  55. Whitespace = r'[ \f\t]*'
  56. Comment = r'#[^\r\n]*'
  57. Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
  58. Name = r'\w+'
  59. Hexnumber = r'0[xX](?:_?[0-9a-fA-F])+'
  60. Binnumber = r'0[bB](?:_?[01])+'
  61. Octnumber = r'0[oO](?:_?[0-7])+'
  62. Decnumber = r'(?:0(?:_?0)*|[1-9](?:_?[0-9])*)'
  63. Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
  64. Exponent = r'[eE][-+]?[0-9](?:_?[0-9])*'
  65. Pointfloat = group(r'[0-9](?:_?[0-9])*\.(?:[0-9](?:_?[0-9])*)?',
  66. r'\.[0-9](?:_?[0-9])*') + maybe(Exponent)
  67. Expfloat = r'[0-9](?:_?[0-9])*' + Exponent
  68. Floatnumber = group(Pointfloat, Expfloat)
  69. Imagnumber = group(r'[0-9](?:_?[0-9])*[jJ]', Floatnumber + r'[jJ]')
  70. Number = group(Imagnumber, Floatnumber, Intnumber)
  71. # Return the empty string, plus all of the valid string prefixes.
  72. def _all_string_prefixes():
  73. # The valid string prefixes. Only contain the lower case versions,
  74. # and don't contain any permutations (include 'fr', but not
  75. # 'rf'). The various permutations will be generated.
  76. _valid_string_prefixes = ['b', 'r', 'u', 'f', 'br', 'fr']
  77. # if we add binary f-strings, add: ['fb', 'fbr']
  78. result = {''}
  79. for prefix in _valid_string_prefixes:
  80. for t in _itertools.permutations(prefix):
  81. # create a list with upper and lower versions of each
  82. # character
  83. for u in _itertools.product(*[(c, c.upper()) for c in t]):
  84. result.add(''.join(u))
  85. return result
  86. @functools.lru_cache
  87. def _compile(expr):
  88. return re.compile(expr, re.UNICODE)
  89. # Note that since _all_string_prefixes includes the empty string,
  90. # StringPrefix can be the empty string (making it optional).
  91. StringPrefix = group(*_all_string_prefixes())
  92. # Tail end of ' string.
  93. Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
  94. # Tail end of " string.
  95. Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
  96. # Tail end of ''' string.
  97. Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
  98. # Tail end of """ string.
  99. Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
  100. Triple = group(StringPrefix + "'''", StringPrefix + '"""')
  101. # Single-line ' or " string.
  102. String = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
  103. StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
  104. # Sorting in reverse order puts the long operators before their prefixes.
  105. # Otherwise if = came before ==, == would get recognized as two instances
  106. # of =.
  107. Special = group(*map(re.escape, sorted(EXACT_TOKEN_TYPES, reverse=True)))
  108. Funny = group(r'\r?\n', Special)
  109. PlainToken = group(Number, Funny, String, Name)
  110. Token = Ignore + PlainToken
  111. # First (or only) line of ' or " string.
  112. ContStr = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
  113. group("'", r'\\\r?\n'),
  114. StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
  115. group('"', r'\\\r?\n'))
  116. PseudoExtras = group(r'\\\r?\n|\Z', Comment, Triple)
  117. PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
  118. # For a given string prefix plus quotes, endpats maps it to a regex
  119. # to match the remainder of that string. _prefix can be empty, for
  120. # a normal single or triple quoted string (with no prefix).
  121. endpats = {}
  122. for _prefix in _all_string_prefixes():
  123. endpats[_prefix + "'"] = Single
  124. endpats[_prefix + '"'] = Double
  125. endpats[_prefix + "'''"] = Single3
  126. endpats[_prefix + '"""'] = Double3
  127. del _prefix
  128. # A set of all of the single and triple quoted string prefixes,
  129. # including the opening quotes.
  130. single_quoted = set()
  131. triple_quoted = set()
  132. for t in _all_string_prefixes():
  133. for u in (t + '"', t + "'"):
  134. single_quoted.add(u)
  135. for u in (t + '"""', t + "'''"):
  136. triple_quoted.add(u)
  137. del t, u
  138. tabsize = 8
  139. class TokenError(Exception): pass
  140. class StopTokenizing(Exception): pass
  141. class Untokenizer:
  142. def __init__(self):
  143. self.tokens = []
  144. self.prev_row = 1
  145. self.prev_col = 0
  146. self.encoding = None
  147. def add_whitespace(self, start):
  148. row, col = start
  149. if row < self.prev_row or row == self.prev_row and col < self.prev_col:
  150. raise ValueError("start ({},{}) precedes previous end ({},{})"
  151. .format(row, col, self.prev_row, self.prev_col))
  152. row_offset = row - self.prev_row
  153. if row_offset:
  154. self.tokens.append("\\\n" * row_offset)
  155. self.prev_col = 0
  156. col_offset = col - self.prev_col
  157. if col_offset:
  158. self.tokens.append(" " * col_offset)
  159. def untokenize(self, iterable):
  160. it = iter(iterable)
  161. indents = []
  162. startline = False
  163. for t in it:
  164. if len(t) == 2:
  165. self.compat(t, it)
  166. break
  167. tok_type, token, start, end, line = t
  168. if tok_type == ENCODING:
  169. self.encoding = token
  170. continue
  171. if tok_type == ENDMARKER:
  172. break
  173. if tok_type == INDENT:
  174. indents.append(token)
  175. continue
  176. elif tok_type == DEDENT:
  177. indents.pop()
  178. self.prev_row, self.prev_col = end
  179. continue
  180. elif tok_type in (NEWLINE, NL):
  181. startline = True
  182. elif startline and indents:
  183. indent = indents[-1]
  184. if start[1] >= len(indent):
  185. self.tokens.append(indent)
  186. self.prev_col = len(indent)
  187. startline = False
  188. elif tok_type == FSTRING_MIDDLE:
  189. if '{' in token or '}' in token:
  190. end_line, end_col = end
  191. end = (end_line, end_col + token.count('{') + token.count('}'))
  192. token = re.sub('{', '{{', token)
  193. token = re.sub('}', '}}', token)
  194. self.add_whitespace(start)
  195. self.tokens.append(token)
  196. self.prev_row, self.prev_col = end
  197. if tok_type in (NEWLINE, NL):
  198. self.prev_row += 1
  199. self.prev_col = 0
  200. return "".join(self.tokens)
  201. def compat(self, token, iterable):
  202. indents = []
  203. toks_append = self.tokens.append
  204. startline = token[0] in (NEWLINE, NL)
  205. prevstring = False
  206. for tok in _itertools.chain([token], iterable):
  207. toknum, tokval = tok[:2]
  208. if toknum == ENCODING:
  209. self.encoding = tokval
  210. continue
  211. if toknum in (NAME, NUMBER):
  212. tokval += ' '
  213. # Insert a space between two consecutive strings
  214. if toknum == STRING:
  215. if prevstring:
  216. tokval = ' ' + tokval
  217. prevstring = True
  218. else:
  219. prevstring = False
  220. if toknum == INDENT:
  221. indents.append(tokval)
  222. continue
  223. elif toknum == DEDENT:
  224. indents.pop()
  225. continue
  226. elif toknum in (NEWLINE, NL):
  227. startline = True
  228. elif startline and indents:
  229. toks_append(indents[-1])
  230. startline = False
  231. elif toknum == FSTRING_MIDDLE:
  232. if '{' in tokval or '}' in tokval:
  233. tokval = re.sub('{', '{{', tokval)
  234. tokval = re.sub('}', '}}', tokval)
  235. toks_append(tokval)
  236. def untokenize(iterable):
  237. """Transform tokens back into Python source code.
  238. It returns a bytes object, encoded using the ENCODING
  239. token, which is the first token sequence output by tokenize.
  240. Each element returned by the iterable must be a token sequence
  241. with at least two elements, a token number and token value. If
  242. only two tokens are passed, the resulting output is poor.
  243. Round-trip invariant for full input:
  244. Untokenized source will match input source exactly
  245. Round-trip invariant for limited input:
  246. # Output bytes will tokenize back to the input
  247. t1 = [tok[:2] for tok in tokenize(f.readline)]
  248. newcode = untokenize(t1)
  249. readline = BytesIO(newcode).readline
  250. t2 = [tok[:2] for tok in tokenize(readline)]
  251. assert t1 == t2
  252. """
  253. ut = Untokenizer()
  254. out = ut.untokenize(iterable)
  255. if ut.encoding is not None:
  256. out = out.encode(ut.encoding)
  257. return out
  258. def _get_normal_name(orig_enc):
  259. """Imitates get_normal_name in tokenizer.c."""
  260. # Only care about the first 12 characters.
  261. enc = orig_enc[:12].lower().replace("_", "-")
  262. if enc == "utf-8" or enc.startswith("utf-8-"):
  263. return "utf-8"
  264. if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
  265. enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
  266. return "iso-8859-1"
  267. return orig_enc
  268. def detect_encoding(readline):
  269. """
  270. The detect_encoding() function is used to detect the encoding that should
  271. be used to decode a Python source file. It requires one argument, readline,
  272. in the same way as the tokenize() generator.
  273. It will call readline a maximum of twice, and return the encoding used
  274. (as a string) and a list of any lines (left as bytes) it has read in.
  275. It detects the encoding from the presence of a utf-8 bom or an encoding
  276. cookie as specified in pep-0263. If both a bom and a cookie are present,
  277. but disagree, a SyntaxError will be raised. If the encoding cookie is an
  278. invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
  279. 'utf-8-sig' is returned.
  280. If no encoding is specified, then the default of 'utf-8' will be returned.
  281. """
  282. try:
  283. filename = readline.__self__.name
  284. except AttributeError:
  285. filename = None
  286. bom_found = False
  287. encoding = None
  288. default = 'utf-8'
  289. def read_or_stop():
  290. try:
  291. return readline()
  292. except StopIteration:
  293. return b''
  294. def find_cookie(line):
  295. try:
  296. # Decode as UTF-8. Either the line is an encoding declaration,
  297. # in which case it should be pure ASCII, or it must be UTF-8
  298. # per default encoding.
  299. line_string = line.decode('utf-8')
  300. except UnicodeDecodeError:
  301. msg = "invalid or missing encoding declaration"
  302. if filename is not None:
  303. msg = '{} for {!r}'.format(msg, filename)
  304. raise SyntaxError(msg)
  305. match = cookie_re.match(line_string)
  306. if not match:
  307. return None
  308. encoding = _get_normal_name(match.group(1))
  309. try:
  310. codec = lookup(encoding)
  311. except LookupError:
  312. # This behaviour mimics the Python interpreter
  313. if filename is None:
  314. msg = "unknown encoding: " + encoding
  315. else:
  316. msg = "unknown encoding for {!r}: {}".format(filename,
  317. encoding)
  318. raise SyntaxError(msg)
  319. if bom_found:
  320. if encoding != 'utf-8':
  321. # This behaviour mimics the Python interpreter
  322. if filename is None:
  323. msg = 'encoding problem: utf-8'
  324. else:
  325. msg = 'encoding problem for {!r}: utf-8'.format(filename)
  326. raise SyntaxError(msg)
  327. encoding += '-sig'
  328. return encoding
  329. first = read_or_stop()
  330. if first.startswith(BOM_UTF8):
  331. bom_found = True
  332. first = first[3:]
  333. default = 'utf-8-sig'
  334. if not first:
  335. return default, []
  336. encoding = find_cookie(first)
  337. if encoding:
  338. return encoding, [first]
  339. if not blank_re.match(first):
  340. return default, [first]
  341. second = read_or_stop()
  342. if not second:
  343. return default, [first]
  344. encoding = find_cookie(second)
  345. if encoding:
  346. return encoding, [first, second]
  347. return default, [first, second]
  348. def open(filename):
  349. """Open a file in read only mode using the encoding detected by
  350. detect_encoding().
  351. """
  352. buffer = _builtin_open(filename, 'rb')
  353. try:
  354. encoding, lines = detect_encoding(buffer.readline)
  355. buffer.seek(0)
  356. text = TextIOWrapper(buffer, encoding, line_buffering=True)
  357. text.mode = 'r'
  358. return text
  359. except:
  360. buffer.close()
  361. raise
  362. def tokenize(readline):
  363. """
  364. The tokenize() generator requires one argument, readline, which
  365. must be a callable object which provides the same interface as the
  366. readline() method of built-in file objects. Each call to the function
  367. should return one line of input as bytes. Alternatively, readline
  368. can be a callable function terminating with StopIteration:
  369. readline = open(myfile, 'rb').__next__ # Example of alternate readline
  370. The generator produces 5-tuples with these members: the token type; the
  371. token string; a 2-tuple (srow, scol) of ints specifying the row and
  372. column where the token begins in the source; a 2-tuple (erow, ecol) of
  373. ints specifying the row and column where the token ends in the source;
  374. and the line on which the token was found. The line passed is the
  375. physical line.
  376. The first token sequence will always be an ENCODING token
  377. which tells you which encoding was used to decode the bytes stream.
  378. """
  379. encoding, consumed = detect_encoding(readline)
  380. rl_gen = _itertools.chain(consumed, iter(readline, b""))
  381. if encoding is not None:
  382. if encoding == "utf-8-sig":
  383. # BOM will already have been stripped.
  384. encoding = "utf-8"
  385. yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '')
  386. yield from _generate_tokens_from_c_tokenizer(rl_gen.__next__, encoding, extra_tokens=True)
  387. def generate_tokens(readline):
  388. """Tokenize a source reading Python code as unicode strings.
  389. This has the same API as tokenize(), except that it expects the *readline*
  390. callable to return str objects instead of bytes.
  391. """
  392. return _generate_tokens_from_c_tokenizer(readline, extra_tokens=True)
  393. def main():
  394. import argparse
  395. # Helper error handling routines
  396. def perror(message):
  397. sys.stderr.write(message)
  398. sys.stderr.write('\n')
  399. def error(message, filename=None, location=None):
  400. if location:
  401. args = (filename,) + location + (message,)
  402. perror("%s:%d:%d: error: %s" % args)
  403. elif filename:
  404. perror("%s: error: %s" % (filename, message))
  405. else:
  406. perror("error: %s" % message)
  407. sys.exit(1)
  408. # Parse the arguments and options
  409. parser = argparse.ArgumentParser(prog='python -m tokenize')
  410. parser.add_argument(dest='filename', nargs='?',
  411. metavar='filename.py',
  412. help='the file to tokenize; defaults to stdin')
  413. parser.add_argument('-e', '--exact', dest='exact', action='store_true',
  414. help='display token names using the exact type')
  415. args = parser.parse_args()
  416. try:
  417. # Tokenize the input
  418. if args.filename:
  419. filename = args.filename
  420. with _builtin_open(filename, 'rb') as f:
  421. tokens = list(tokenize(f.readline))
  422. else:
  423. filename = "<stdin>"
  424. tokens = _generate_tokens_from_c_tokenizer(
  425. sys.stdin.readline, extra_tokens=True)
  426. # Output the tokenization
  427. for token in tokens:
  428. token_type = token.type
  429. if args.exact:
  430. token_type = token.exact_type
  431. token_range = "%d,%d-%d,%d:" % (token.start + token.end)
  432. print("%-20s%-15s%-15r" %
  433. (token_range, tok_name[token_type], token.string))
  434. except IndentationError as err:
  435. line, column = err.args[1][1:3]
  436. error(err.args[0], filename, (line, column))
  437. except TokenError as err:
  438. line, column = err.args[1]
  439. error(err.args[0], filename, (line, column))
  440. except SyntaxError as err:
  441. error(err, filename)
  442. except OSError as err:
  443. error(err)
  444. except KeyboardInterrupt:
  445. print("interrupted\n")
  446. except Exception as err:
  447. perror("unexpected error: %s" % err)
  448. raise
  449. def _transform_msg(msg):
  450. """Transform error messages from the C tokenizer into the Python tokenize
  451. The C tokenizer is more picky than the Python one, so we need to massage
  452. the error messages a bit for backwards compatibility.
  453. """
  454. if "unterminated triple-quoted string literal" in msg:
  455. return "EOF in multi-line string"
  456. return msg
  457. def _generate_tokens_from_c_tokenizer(source, encoding=None, extra_tokens=False):
  458. """Tokenize a source reading Python code as unicode strings using the internal C tokenizer"""
  459. if encoding is None:
  460. it = _tokenize.TokenizerIter(source, extra_tokens=extra_tokens)
  461. else:
  462. it = _tokenize.TokenizerIter(source, encoding=encoding, extra_tokens=extra_tokens)
  463. try:
  464. for info in it:
  465. yield TokenInfo._make(info)
  466. except SyntaxError as e:
  467. if type(e) != SyntaxError:
  468. raise e from None
  469. msg = _transform_msg(e.msg)
  470. raise TokenError(msg, (e.lineno, e.offset)) from None
  471. if __name__ == "__main__":
  472. main()