tokenize.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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.prev_type = None
  147. self.encoding = None
  148. def add_whitespace(self, start):
  149. row, col = start
  150. if row < self.prev_row or row == self.prev_row and col < self.prev_col:
  151. raise ValueError("start ({},{}) precedes previous end ({},{})"
  152. .format(row, col, self.prev_row, self.prev_col))
  153. row_offset = row - self.prev_row
  154. if row_offset:
  155. self.tokens.append("\\\n" * row_offset)
  156. self.prev_col = 0
  157. col_offset = col - self.prev_col
  158. if col_offset:
  159. self.tokens.append(" " * col_offset)
  160. def escape_brackets(self, token):
  161. characters = []
  162. consume_until_next_bracket = False
  163. for character in token:
  164. if character == "}":
  165. if consume_until_next_bracket:
  166. consume_until_next_bracket = False
  167. else:
  168. characters.append(character)
  169. if character == "{":
  170. n_backslashes = sum(
  171. 1 for char in _itertools.takewhile(
  172. "\\".__eq__,
  173. characters[-2::-1]
  174. )
  175. )
  176. if n_backslashes % 2 == 0:
  177. characters.append(character)
  178. else:
  179. consume_until_next_bracket = True
  180. characters.append(character)
  181. return "".join(characters)
  182. def untokenize(self, iterable):
  183. it = iter(iterable)
  184. indents = []
  185. startline = False
  186. for t in it:
  187. if len(t) == 2:
  188. self.compat(t, it)
  189. break
  190. tok_type, token, start, end, line = t
  191. if tok_type == ENCODING:
  192. self.encoding = token
  193. continue
  194. if tok_type == ENDMARKER:
  195. break
  196. if tok_type == INDENT:
  197. indents.append(token)
  198. continue
  199. elif tok_type == DEDENT:
  200. indents.pop()
  201. self.prev_row, self.prev_col = end
  202. continue
  203. elif tok_type in (NEWLINE, NL):
  204. startline = True
  205. elif startline and indents:
  206. indent = indents[-1]
  207. if start[1] >= len(indent):
  208. self.tokens.append(indent)
  209. self.prev_col = len(indent)
  210. startline = False
  211. elif tok_type == FSTRING_MIDDLE:
  212. if '{' in token or '}' in token:
  213. token = self.escape_brackets(token)
  214. last_line = token.splitlines()[-1]
  215. end_line, end_col = end
  216. extra_chars = last_line.count("{{") + last_line.count("}}")
  217. end = (end_line, end_col + extra_chars)
  218. elif tok_type in (STRING, FSTRING_START) and self.prev_type in (STRING, FSTRING_END):
  219. self.tokens.append(" ")
  220. self.add_whitespace(start)
  221. self.tokens.append(token)
  222. self.prev_row, self.prev_col = end
  223. if tok_type in (NEWLINE, NL):
  224. self.prev_row += 1
  225. self.prev_col = 0
  226. self.prev_type = tok_type
  227. return "".join(self.tokens)
  228. def compat(self, token, iterable):
  229. indents = []
  230. toks_append = self.tokens.append
  231. startline = token[0] in (NEWLINE, NL)
  232. prevstring = False
  233. in_fstring = 0
  234. for tok in _itertools.chain([token], iterable):
  235. toknum, tokval = tok[:2]
  236. if toknum == ENCODING:
  237. self.encoding = tokval
  238. continue
  239. if toknum in (NAME, NUMBER):
  240. tokval += ' '
  241. # Insert a space between two consecutive strings
  242. if toknum == STRING:
  243. if prevstring:
  244. tokval = ' ' + tokval
  245. prevstring = True
  246. else:
  247. prevstring = False
  248. if toknum == FSTRING_START:
  249. in_fstring += 1
  250. elif toknum == FSTRING_END:
  251. in_fstring -= 1
  252. if toknum == INDENT:
  253. indents.append(tokval)
  254. continue
  255. elif toknum == DEDENT:
  256. indents.pop()
  257. continue
  258. elif toknum in (NEWLINE, NL):
  259. startline = True
  260. elif startline and indents:
  261. toks_append(indents[-1])
  262. startline = False
  263. elif toknum == FSTRING_MIDDLE:
  264. tokval = self.escape_brackets(tokval)
  265. # Insert a space between two consecutive brackets if we are in an f-string
  266. if tokval in {"{", "}"} and self.tokens and self.tokens[-1] == tokval and in_fstring:
  267. tokval = ' ' + tokval
  268. # Insert a space between two consecutive f-strings
  269. if toknum in (STRING, FSTRING_START) and self.prev_type in (STRING, FSTRING_END):
  270. self.tokens.append(" ")
  271. toks_append(tokval)
  272. self.prev_type = toknum
  273. def untokenize(iterable):
  274. """Transform tokens back into Python source code.
  275. It returns a bytes object, encoded using the ENCODING
  276. token, which is the first token sequence output by tokenize.
  277. Each element returned by the iterable must be a token sequence
  278. with at least two elements, a token number and token value. If
  279. only two tokens are passed, the resulting output is poor.
  280. Round-trip invariant for full input:
  281. Untokenized source will match input source exactly
  282. Round-trip invariant for limited input:
  283. # Output bytes will tokenize back to the input
  284. t1 = [tok[:2] for tok in tokenize(f.readline)]
  285. newcode = untokenize(t1)
  286. readline = BytesIO(newcode).readline
  287. t2 = [tok[:2] for tok in tokenize(readline)]
  288. assert t1 == t2
  289. """
  290. ut = Untokenizer()
  291. out = ut.untokenize(iterable)
  292. if ut.encoding is not None:
  293. out = out.encode(ut.encoding)
  294. return out
  295. def _get_normal_name(orig_enc):
  296. """Imitates get_normal_name in tokenizer.c."""
  297. # Only care about the first 12 characters.
  298. enc = orig_enc[:12].lower().replace("_", "-")
  299. if enc == "utf-8" or enc.startswith("utf-8-"):
  300. return "utf-8"
  301. if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
  302. enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
  303. return "iso-8859-1"
  304. return orig_enc
  305. def detect_encoding(readline):
  306. """
  307. The detect_encoding() function is used to detect the encoding that should
  308. be used to decode a Python source file. It requires one argument, readline,
  309. in the same way as the tokenize() generator.
  310. It will call readline a maximum of twice, and return the encoding used
  311. (as a string) and a list of any lines (left as bytes) it has read in.
  312. It detects the encoding from the presence of a utf-8 bom or an encoding
  313. cookie as specified in pep-0263. If both a bom and a cookie are present,
  314. but disagree, a SyntaxError will be raised. If the encoding cookie is an
  315. invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
  316. 'utf-8-sig' is returned.
  317. If no encoding is specified, then the default of 'utf-8' will be returned.
  318. """
  319. try:
  320. filename = readline.__self__.name
  321. except AttributeError:
  322. filename = None
  323. bom_found = False
  324. encoding = None
  325. default = 'utf-8'
  326. def read_or_stop():
  327. try:
  328. return readline()
  329. except StopIteration:
  330. return b''
  331. def find_cookie(line):
  332. try:
  333. # Decode as UTF-8. Either the line is an encoding declaration,
  334. # in which case it should be pure ASCII, or it must be UTF-8
  335. # per default encoding.
  336. line_string = line.decode('utf-8')
  337. except UnicodeDecodeError:
  338. msg = "invalid or missing encoding declaration"
  339. if filename is not None:
  340. msg = '{} for {!r}'.format(msg, filename)
  341. raise SyntaxError(msg)
  342. match = cookie_re.match(line_string)
  343. if not match:
  344. return None
  345. encoding = _get_normal_name(match.group(1))
  346. try:
  347. codec = lookup(encoding)
  348. except LookupError:
  349. # This behaviour mimics the Python interpreter
  350. if filename is None:
  351. msg = "unknown encoding: " + encoding
  352. else:
  353. msg = "unknown encoding for {!r}: {}".format(filename,
  354. encoding)
  355. raise SyntaxError(msg)
  356. if bom_found:
  357. if encoding != 'utf-8':
  358. # This behaviour mimics the Python interpreter
  359. if filename is None:
  360. msg = 'encoding problem: utf-8'
  361. else:
  362. msg = 'encoding problem for {!r}: utf-8'.format(filename)
  363. raise SyntaxError(msg)
  364. encoding += '-sig'
  365. return encoding
  366. first = read_or_stop()
  367. if first.startswith(BOM_UTF8):
  368. bom_found = True
  369. first = first[3:]
  370. default = 'utf-8-sig'
  371. if not first:
  372. return default, []
  373. encoding = find_cookie(first)
  374. if encoding:
  375. return encoding, [first]
  376. if not blank_re.match(first):
  377. return default, [first]
  378. second = read_or_stop()
  379. if not second:
  380. return default, [first]
  381. encoding = find_cookie(second)
  382. if encoding:
  383. return encoding, [first, second]
  384. return default, [first, second]
  385. def open(filename):
  386. """Open a file in read only mode using the encoding detected by
  387. detect_encoding().
  388. """
  389. buffer = _builtin_open(filename, 'rb')
  390. try:
  391. encoding, lines = detect_encoding(buffer.readline)
  392. buffer.seek(0)
  393. text = TextIOWrapper(buffer, encoding, line_buffering=True)
  394. text.mode = 'r'
  395. return text
  396. except:
  397. buffer.close()
  398. raise
  399. def tokenize(readline):
  400. """
  401. The tokenize() generator requires one argument, readline, which
  402. must be a callable object which provides the same interface as the
  403. readline() method of built-in file objects. Each call to the function
  404. should return one line of input as bytes. Alternatively, readline
  405. can be a callable function terminating with StopIteration:
  406. readline = open(myfile, 'rb').__next__ # Example of alternate readline
  407. The generator produces 5-tuples with these members: the token type; the
  408. token string; a 2-tuple (srow, scol) of ints specifying the row and
  409. column where the token begins in the source; a 2-tuple (erow, ecol) of
  410. ints specifying the row and column where the token ends in the source;
  411. and the line on which the token was found. The line passed is the
  412. physical line.
  413. The first token sequence will always be an ENCODING token
  414. which tells you which encoding was used to decode the bytes stream.
  415. """
  416. encoding, consumed = detect_encoding(readline)
  417. rl_gen = _itertools.chain(consumed, iter(readline, b""))
  418. if encoding is not None:
  419. if encoding == "utf-8-sig":
  420. # BOM will already have been stripped.
  421. encoding = "utf-8"
  422. yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '')
  423. yield from _generate_tokens_from_c_tokenizer(rl_gen.__next__, encoding, extra_tokens=True)
  424. def generate_tokens(readline):
  425. """Tokenize a source reading Python code as unicode strings.
  426. This has the same API as tokenize(), except that it expects the *readline*
  427. callable to return str objects instead of bytes.
  428. """
  429. return _generate_tokens_from_c_tokenizer(readline, extra_tokens=True)
  430. def main():
  431. import argparse
  432. # Helper error handling routines
  433. def perror(message):
  434. sys.stderr.write(message)
  435. sys.stderr.write('\n')
  436. def error(message, filename=None, location=None):
  437. if location:
  438. args = (filename,) + location + (message,)
  439. perror("%s:%d:%d: error: %s" % args)
  440. elif filename:
  441. perror("%s: error: %s" % (filename, message))
  442. else:
  443. perror("error: %s" % message)
  444. sys.exit(1)
  445. # Parse the arguments and options
  446. parser = argparse.ArgumentParser(prog='python -m tokenize')
  447. parser.add_argument(dest='filename', nargs='?',
  448. metavar='filename.py',
  449. help='the file to tokenize; defaults to stdin')
  450. parser.add_argument('-e', '--exact', dest='exact', action='store_true',
  451. help='display token names using the exact type')
  452. args = parser.parse_args()
  453. try:
  454. # Tokenize the input
  455. if args.filename:
  456. filename = args.filename
  457. with _builtin_open(filename, 'rb') as f:
  458. tokens = list(tokenize(f.readline))
  459. else:
  460. filename = "<stdin>"
  461. tokens = _generate_tokens_from_c_tokenizer(
  462. sys.stdin.readline, extra_tokens=True)
  463. # Output the tokenization
  464. for token in tokens:
  465. token_type = token.type
  466. if args.exact:
  467. token_type = token.exact_type
  468. token_range = "%d,%d-%d,%d:" % (token.start + token.end)
  469. print("%-20s%-15s%-15r" %
  470. (token_range, tok_name[token_type], token.string))
  471. except IndentationError as err:
  472. line, column = err.args[1][1:3]
  473. error(err.args[0], filename, (line, column))
  474. except TokenError as err:
  475. line, column = err.args[1]
  476. error(err.args[0], filename, (line, column))
  477. except SyntaxError as err:
  478. error(err, filename)
  479. except OSError as err:
  480. error(err)
  481. except KeyboardInterrupt:
  482. print("interrupted\n")
  483. except Exception as err:
  484. perror("unexpected error: %s" % err)
  485. raise
  486. def _transform_msg(msg):
  487. """Transform error messages from the C tokenizer into the Python tokenize
  488. The C tokenizer is more picky than the Python one, so we need to massage
  489. the error messages a bit for backwards compatibility.
  490. """
  491. if "unterminated triple-quoted string literal" in msg:
  492. return "EOF in multi-line string"
  493. return msg
  494. def _generate_tokens_from_c_tokenizer(source, encoding=None, extra_tokens=False):
  495. """Tokenize a source reading Python code as unicode strings using the internal C tokenizer"""
  496. if encoding is None:
  497. it = _tokenize.TokenizerIter(source, extra_tokens=extra_tokens)
  498. else:
  499. it = _tokenize.TokenizerIter(source, encoding=encoding, extra_tokens=extra_tokens)
  500. try:
  501. for info in it:
  502. yield TokenInfo._make(info)
  503. except SyntaxError as e:
  504. if type(e) != SyntaxError:
  505. raise e from None
  506. msg = _transform_msg(e.msg)
  507. raise TokenError(msg, (e.lineno, e.offset)) from None
  508. if __name__ == "__main__":
  509. main()