tokenize.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  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. from io import TextIOWrapper
  26. from itertools import chain
  27. import re
  28. import sys
  29. from token import *
  30. cookie_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII)
  31. blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII)
  32. import token
  33. __all__ = token.__all__ + ["COMMENT", "tokenize", "detect_encoding",
  34. "NL", "untokenize", "ENCODING", "TokenInfo"]
  35. del token
  36. COMMENT = N_TOKENS
  37. tok_name[COMMENT] = 'COMMENT'
  38. NL = N_TOKENS + 1
  39. tok_name[NL] = 'NL'
  40. ENCODING = N_TOKENS + 2
  41. tok_name[ENCODING] = 'ENCODING'
  42. N_TOKENS += 3
  43. EXACT_TOKEN_TYPES = {
  44. '(': LPAR,
  45. ')': RPAR,
  46. '[': LSQB,
  47. ']': RSQB,
  48. ':': COLON,
  49. ',': COMMA,
  50. ';': SEMI,
  51. '+': PLUS,
  52. '-': MINUS,
  53. '*': STAR,
  54. '/': SLASH,
  55. '|': VBAR,
  56. '&': AMPER,
  57. '<': LESS,
  58. '>': GREATER,
  59. '=': EQUAL,
  60. '.': DOT,
  61. '%': PERCENT,
  62. '{': LBRACE,
  63. '}': RBRACE,
  64. '==': EQEQUAL,
  65. '!=': NOTEQUAL,
  66. '<=': LESSEQUAL,
  67. '>=': GREATEREQUAL,
  68. '~': TILDE,
  69. '^': CIRCUMFLEX,
  70. '<<': LEFTSHIFT,
  71. '>>': RIGHTSHIFT,
  72. '**': DOUBLESTAR,
  73. '+=': PLUSEQUAL,
  74. '-=': MINEQUAL,
  75. '*=': STAREQUAL,
  76. '/=': SLASHEQUAL,
  77. '%=': PERCENTEQUAL,
  78. '&=': AMPEREQUAL,
  79. '|=': VBAREQUAL,
  80. '^=': CIRCUMFLEXEQUAL,
  81. '<<=': LEFTSHIFTEQUAL,
  82. '>>=': RIGHTSHIFTEQUAL,
  83. '**=': DOUBLESTAREQUAL,
  84. '//': DOUBLESLASH,
  85. '//=': DOUBLESLASHEQUAL,
  86. '@': AT,
  87. '@=': ATEQUAL,
  88. }
  89. class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
  90. def __repr__(self):
  91. annotated_type = '%d (%s)' % (self.type, tok_name[self.type])
  92. return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' %
  93. self._replace(type=annotated_type))
  94. @property
  95. def exact_type(self):
  96. if self.type == OP and self.string in EXACT_TOKEN_TYPES:
  97. return EXACT_TOKEN_TYPES[self.string]
  98. else:
  99. return self.type
  100. def group(*choices): return '(' + '|'.join(choices) + ')'
  101. def any(*choices): return group(*choices) + '*'
  102. def maybe(*choices): return group(*choices) + '?'
  103. # Note: we use unicode matching for names ("\w") but ascii matching for
  104. # number literals.
  105. Whitespace = r'[ \f\t]*'
  106. Comment = r'#[^\r\n]*'
  107. Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
  108. Name = r'\w+'
  109. Hexnumber = r'0[xX][0-9a-fA-F]+'
  110. Binnumber = r'0[bB][01]+'
  111. Octnumber = r'0[oO][0-7]+'
  112. Decnumber = r'(?:0+|[1-9][0-9]*)'
  113. Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
  114. Exponent = r'[eE][-+]?[0-9]+'
  115. Pointfloat = group(r'[0-9]+\.[0-9]*', r'\.[0-9]+') + maybe(Exponent)
  116. Expfloat = r'[0-9]+' + Exponent
  117. Floatnumber = group(Pointfloat, Expfloat)
  118. Imagnumber = group(r'[0-9]+[jJ]', Floatnumber + r'[jJ]')
  119. Number = group(Imagnumber, Floatnumber, Intnumber)
  120. StringPrefix = r'(?:[bB][rR]?|[rR][bB]?|[uU])?'
  121. # Tail end of ' string.
  122. Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
  123. # Tail end of " string.
  124. Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
  125. # Tail end of ''' string.
  126. Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
  127. # Tail end of """ string.
  128. Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
  129. Triple = group(StringPrefix + "'''", StringPrefix + '"""')
  130. # Single-line ' or " string.
  131. String = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
  132. StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
  133. # Because of leftmost-then-longest match semantics, be sure to put the
  134. # longest operators first (e.g., if = came before ==, == would get
  135. # recognized as two instances of =).
  136. Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=",
  137. r"//=?", r"->",
  138. r"[+\-*/%&@|^=<>]=?",
  139. r"~")
  140. Bracket = '[][(){}]'
  141. Special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]')
  142. Funny = group(Operator, Bracket, Special)
  143. PlainToken = group(Number, Funny, String, Name)
  144. Token = Ignore + PlainToken
  145. # First (or only) line of ' or " string.
  146. ContStr = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
  147. group("'", r'\\\r?\n'),
  148. StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
  149. group('"', r'\\\r?\n'))
  150. PseudoExtras = group(r'\\\r?\n|\Z', Comment, Triple)
  151. PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
  152. def _compile(expr):
  153. return re.compile(expr, re.UNICODE)
  154. endpats = {"'": Single, '"': Double,
  155. "'''": Single3, '"""': Double3,
  156. "r'''": Single3, 'r"""': Double3,
  157. "b'''": Single3, 'b"""': Double3,
  158. "R'''": Single3, 'R"""': Double3,
  159. "B'''": Single3, 'B"""': Double3,
  160. "br'''": Single3, 'br"""': Double3,
  161. "bR'''": Single3, 'bR"""': Double3,
  162. "Br'''": Single3, 'Br"""': Double3,
  163. "BR'''": Single3, 'BR"""': Double3,
  164. "rb'''": Single3, 'rb"""': Double3,
  165. "Rb'''": Single3, 'Rb"""': Double3,
  166. "rB'''": Single3, 'rB"""': Double3,
  167. "RB'''": Single3, 'RB"""': Double3,
  168. "u'''": Single3, 'u"""': Double3,
  169. "U'''": Single3, 'U"""': Double3,
  170. 'r': None, 'R': None, 'b': None, 'B': None,
  171. 'u': None, 'U': None}
  172. triple_quoted = {}
  173. for t in ("'''", '"""',
  174. "r'''", 'r"""', "R'''", 'R"""',
  175. "b'''", 'b"""', "B'''", 'B"""',
  176. "br'''", 'br"""', "Br'''", 'Br"""',
  177. "bR'''", 'bR"""', "BR'''", 'BR"""',
  178. "rb'''", 'rb"""', "rB'''", 'rB"""',
  179. "Rb'''", 'Rb"""', "RB'''", 'RB"""',
  180. "u'''", 'u"""', "U'''", 'U"""',
  181. ):
  182. triple_quoted[t] = t
  183. single_quoted = {}
  184. for t in ("'", '"',
  185. "r'", 'r"', "R'", 'R"',
  186. "b'", 'b"', "B'", 'B"',
  187. "br'", 'br"', "Br'", 'Br"',
  188. "bR'", 'bR"', "BR'", 'BR"' ,
  189. "rb'", 'rb"', "rB'", 'rB"',
  190. "Rb'", 'Rb"', "RB'", 'RB"' ,
  191. "u'", 'u"', "U'", 'U"',
  192. ):
  193. single_quoted[t] = t
  194. tabsize = 8
  195. class TokenError(Exception): pass
  196. class StopTokenizing(Exception): pass
  197. class Untokenizer:
  198. def __init__(self):
  199. self.tokens = []
  200. self.prev_row = 1
  201. self.prev_col = 0
  202. self.encoding = None
  203. def add_whitespace(self, start):
  204. row, col = start
  205. if row < self.prev_row or row == self.prev_row and col < self.prev_col:
  206. raise ValueError("start ({},{}) precedes previous end ({},{})"
  207. .format(row, col, self.prev_row, self.prev_col))
  208. row_offset = row - self.prev_row
  209. if row_offset:
  210. self.tokens.append("\\\n" * row_offset)
  211. self.prev_col = 0
  212. col_offset = col - self.prev_col
  213. if col_offset:
  214. self.tokens.append(" " * col_offset)
  215. def untokenize(self, iterable):
  216. it = iter(iterable)
  217. indents = []
  218. startline = False
  219. for t in it:
  220. if len(t) == 2:
  221. self.compat(t, it)
  222. break
  223. tok_type, token, start, end, line = t
  224. if tok_type == ENCODING:
  225. self.encoding = token
  226. continue
  227. if tok_type == ENDMARKER:
  228. break
  229. if tok_type == INDENT:
  230. indents.append(token)
  231. continue
  232. elif tok_type == DEDENT:
  233. indents.pop()
  234. self.prev_row, self.prev_col = end
  235. continue
  236. elif tok_type in (NEWLINE, NL):
  237. startline = True
  238. elif startline and indents:
  239. indent = indents[-1]
  240. if start[1] >= len(indent):
  241. self.tokens.append(indent)
  242. self.prev_col = len(indent)
  243. startline = False
  244. self.add_whitespace(start)
  245. self.tokens.append(token)
  246. self.prev_row, self.prev_col = end
  247. if tok_type in (NEWLINE, NL):
  248. self.prev_row += 1
  249. self.prev_col = 0
  250. return "".join(self.tokens)
  251. def compat(self, token, iterable):
  252. indents = []
  253. toks_append = self.tokens.append
  254. startline = token[0] in (NEWLINE, NL)
  255. prevstring = False
  256. for tok in chain([token], iterable):
  257. toknum, tokval = tok[:2]
  258. if toknum == ENCODING:
  259. self.encoding = tokval
  260. continue
  261. if toknum in (NAME, NUMBER, ASYNC, AWAIT):
  262. tokval += ' '
  263. # Insert a space between two consecutive strings
  264. if toknum == STRING:
  265. if prevstring:
  266. tokval = ' ' + tokval
  267. prevstring = True
  268. else:
  269. prevstring = False
  270. if toknum == INDENT:
  271. indents.append(tokval)
  272. continue
  273. elif toknum == DEDENT:
  274. indents.pop()
  275. continue
  276. elif toknum in (NEWLINE, NL):
  277. startline = True
  278. elif startline and indents:
  279. toks_append(indents[-1])
  280. startline = False
  281. toks_append(tokval)
  282. def untokenize(iterable):
  283. """Transform tokens back into Python source code.
  284. It returns a bytes object, encoded using the ENCODING
  285. token, which is the first token sequence output by tokenize.
  286. Each element returned by the iterable must be a token sequence
  287. with at least two elements, a token number and token value. If
  288. only two tokens are passed, the resulting output is poor.
  289. Round-trip invariant for full input:
  290. Untokenized source will match input source exactly
  291. Round-trip invariant for limited input:
  292. # Output bytes will tokenize back to the input
  293. t1 = [tok[:2] for tok in tokenize(f.readline)]
  294. newcode = untokenize(t1)
  295. readline = BytesIO(newcode).readline
  296. t2 = [tok[:2] for tok in tokenize(readline)]
  297. assert t1 == t2
  298. """
  299. ut = Untokenizer()
  300. out = ut.untokenize(iterable)
  301. if ut.encoding is not None:
  302. out = out.encode(ut.encoding)
  303. return out
  304. def _get_normal_name(orig_enc):
  305. """Imitates get_normal_name in tokenizer.c."""
  306. # Only care about the first 12 characters.
  307. enc = orig_enc[:12].lower().replace("_", "-")
  308. if enc == "utf-8" or enc.startswith("utf-8-"):
  309. return "utf-8"
  310. if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
  311. enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
  312. return "iso-8859-1"
  313. return orig_enc
  314. def detect_encoding(readline):
  315. """
  316. The detect_encoding() function is used to detect the encoding that should
  317. be used to decode a Python source file. It requires one argument, readline,
  318. in the same way as the tokenize() generator.
  319. It will call readline a maximum of twice, and return the encoding used
  320. (as a string) and a list of any lines (left as bytes) it has read in.
  321. It detects the encoding from the presence of a utf-8 bom or an encoding
  322. cookie as specified in pep-0263. If both a bom and a cookie are present,
  323. but disagree, a SyntaxError will be raised. If the encoding cookie is an
  324. invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
  325. 'utf-8-sig' is returned.
  326. If no encoding is specified, then the default of 'utf-8' will be returned.
  327. """
  328. try:
  329. filename = readline.__self__.name
  330. except AttributeError:
  331. filename = None
  332. bom_found = False
  333. encoding = None
  334. default = 'utf-8'
  335. def read_or_stop():
  336. try:
  337. return readline()
  338. except StopIteration:
  339. return b''
  340. def find_cookie(line):
  341. try:
  342. # Decode as UTF-8. Either the line is an encoding declaration,
  343. # in which case it should be pure ASCII, or it must be UTF-8
  344. # per default encoding.
  345. line_string = line.decode('utf-8')
  346. except UnicodeDecodeError:
  347. msg = "invalid or missing encoding declaration"
  348. if filename is not None:
  349. msg = '{} for {!r}'.format(msg, filename)
  350. raise SyntaxError(msg)
  351. match = cookie_re.match(line_string)
  352. if not match:
  353. return None
  354. encoding = _get_normal_name(match.group(1))
  355. try:
  356. codec = lookup(encoding)
  357. except LookupError:
  358. # This behaviour mimics the Python interpreter
  359. if filename is None:
  360. msg = "unknown encoding: " + encoding
  361. else:
  362. msg = "unknown encoding for {!r}: {}".format(filename,
  363. encoding)
  364. raise SyntaxError(msg)
  365. if bom_found:
  366. if encoding != 'utf-8':
  367. # This behaviour mimics the Python interpreter
  368. if filename is None:
  369. msg = 'encoding problem: utf-8'
  370. else:
  371. msg = 'encoding problem for {!r}: utf-8'.format(filename)
  372. raise SyntaxError(msg)
  373. encoding += '-sig'
  374. return encoding
  375. first = read_or_stop()
  376. if first.startswith(BOM_UTF8):
  377. bom_found = True
  378. first = first[3:]
  379. default = 'utf-8-sig'
  380. if not first:
  381. return default, []
  382. encoding = find_cookie(first)
  383. if encoding:
  384. return encoding, [first]
  385. if not blank_re.match(first):
  386. return default, [first]
  387. second = read_or_stop()
  388. if not second:
  389. return default, [first]
  390. encoding = find_cookie(second)
  391. if encoding:
  392. return encoding, [first, second]
  393. return default, [first, second]
  394. def open(filename):
  395. """Open a file in read only mode using the encoding detected by
  396. detect_encoding().
  397. """
  398. buffer = _builtin_open(filename, 'rb')
  399. try:
  400. encoding, lines = detect_encoding(buffer.readline)
  401. buffer.seek(0)
  402. text = TextIOWrapper(buffer, encoding, line_buffering=True)
  403. text.mode = 'r'
  404. return text
  405. except:
  406. buffer.close()
  407. raise
  408. def tokenize(readline):
  409. """
  410. The tokenize() generator requires one argument, readline, which
  411. must be a callable object which provides the same interface as the
  412. readline() method of built-in file objects. Each call to the function
  413. should return one line of input as bytes. Alternatively, readline
  414. can be a callable function terminating with StopIteration:
  415. readline = open(myfile, 'rb').__next__ # Example of alternate readline
  416. The generator produces 5-tuples with these members: the token type; the
  417. token string; a 2-tuple (srow, scol) of ints specifying the row and
  418. column where the token begins in the source; a 2-tuple (erow, ecol) of
  419. ints specifying the row and column where the token ends in the source;
  420. and the line on which the token was found. The line passed is the
  421. logical line; continuation lines are included.
  422. The first token sequence will always be an ENCODING token
  423. which tells you which encoding was used to decode the bytes stream.
  424. """
  425. # This import is here to avoid problems when the itertools module is not
  426. # built yet and tokenize is imported.
  427. from itertools import chain, repeat
  428. encoding, consumed = detect_encoding(readline)
  429. rl_gen = iter(readline, b"")
  430. empty = repeat(b"")
  431. return _tokenize(chain(consumed, rl_gen, empty).__next__, encoding)
  432. def _tokenize(readline, encoding):
  433. lnum = parenlev = continued = 0
  434. numchars = '0123456789'
  435. contstr, needcont = '', 0
  436. contline = None
  437. indents = [0]
  438. # 'stashed' and 'async_*' are used for async/await parsing
  439. stashed = None
  440. async_def = False
  441. async_def_indent = 0
  442. async_def_nl = False
  443. if encoding is not None:
  444. if encoding == "utf-8-sig":
  445. # BOM will already have been stripped.
  446. encoding = "utf-8"
  447. yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '')
  448. while True: # loop over lines in stream
  449. try:
  450. line = readline()
  451. except StopIteration:
  452. line = b''
  453. if encoding is not None:
  454. line = line.decode(encoding)
  455. lnum += 1
  456. pos, max = 0, len(line)
  457. if contstr: # continued string
  458. if not line:
  459. raise TokenError("EOF in multi-line string", strstart)
  460. endmatch = endprog.match(line)
  461. if endmatch:
  462. pos = end = endmatch.end(0)
  463. yield TokenInfo(STRING, contstr + line[:end],
  464. strstart, (lnum, end), contline + line)
  465. contstr, needcont = '', 0
  466. contline = None
  467. elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
  468. yield TokenInfo(ERRORTOKEN, contstr + line,
  469. strstart, (lnum, len(line)), contline)
  470. contstr = ''
  471. contline = None
  472. continue
  473. else:
  474. contstr = contstr + line
  475. contline = contline + line
  476. continue
  477. elif parenlev == 0 and not continued: # new statement
  478. if not line: break
  479. column = 0
  480. while pos < max: # measure leading whitespace
  481. if line[pos] == ' ':
  482. column += 1
  483. elif line[pos] == '\t':
  484. column = (column//tabsize + 1)*tabsize
  485. elif line[pos] == '\f':
  486. column = 0
  487. else:
  488. break
  489. pos += 1
  490. if pos == max:
  491. break
  492. if line[pos] in '#\r\n': # skip comments or blank lines
  493. if line[pos] == '#':
  494. comment_token = line[pos:].rstrip('\r\n')
  495. nl_pos = pos + len(comment_token)
  496. yield TokenInfo(COMMENT, comment_token,
  497. (lnum, pos), (lnum, pos + len(comment_token)), line)
  498. yield TokenInfo(NL, line[nl_pos:],
  499. (lnum, nl_pos), (lnum, len(line)), line)
  500. else:
  501. yield TokenInfo((NL, COMMENT)[line[pos] == '#'], line[pos:],
  502. (lnum, pos), (lnum, len(line)), line)
  503. continue
  504. if column > indents[-1]: # count indents or dedents
  505. indents.append(column)
  506. yield TokenInfo(INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
  507. while column < indents[-1]:
  508. if column not in indents:
  509. raise IndentationError(
  510. "unindent does not match any outer indentation level",
  511. ("<tokenize>", lnum, pos, line))
  512. indents = indents[:-1]
  513. if async_def and async_def_indent >= indents[-1]:
  514. async_def = False
  515. async_def_nl = False
  516. async_def_indent = 0
  517. yield TokenInfo(DEDENT, '', (lnum, pos), (lnum, pos), line)
  518. if async_def and async_def_nl and async_def_indent >= indents[-1]:
  519. async_def = False
  520. async_def_nl = False
  521. async_def_indent = 0
  522. else: # continued statement
  523. if not line:
  524. raise TokenError("EOF in multi-line statement", (lnum, 0))
  525. continued = 0
  526. while pos < max:
  527. pseudomatch = _compile(PseudoToken).match(line, pos)
  528. if pseudomatch: # scan for tokens
  529. start, end = pseudomatch.span(1)
  530. spos, epos, pos = (lnum, start), (lnum, end), end
  531. if start == end:
  532. continue
  533. token, initial = line[start:end], line[start]
  534. if (initial in numchars or # ordinary number
  535. (initial == '.' and token != '.' and token != '...')):
  536. yield TokenInfo(NUMBER, token, spos, epos, line)
  537. elif initial in '\r\n':
  538. if stashed:
  539. yield stashed
  540. stashed = None
  541. if parenlev > 0:
  542. yield TokenInfo(NL, token, spos, epos, line)
  543. else:
  544. yield TokenInfo(NEWLINE, token, spos, epos, line)
  545. if async_def:
  546. async_def_nl = True
  547. elif initial == '#':
  548. assert not token.endswith("\n")
  549. if stashed:
  550. yield stashed
  551. stashed = None
  552. yield TokenInfo(COMMENT, token, spos, epos, line)
  553. elif token in triple_quoted:
  554. endprog = _compile(endpats[token])
  555. endmatch = endprog.match(line, pos)
  556. if endmatch: # all on one line
  557. pos = endmatch.end(0)
  558. token = line[start:pos]
  559. yield TokenInfo(STRING, token, spos, (lnum, pos), line)
  560. else:
  561. strstart = (lnum, start) # multiple lines
  562. contstr = line[start:]
  563. contline = line
  564. break
  565. elif initial in single_quoted or \
  566. token[:2] in single_quoted or \
  567. token[:3] in single_quoted:
  568. if token[-1] == '\n': # continued string
  569. strstart = (lnum, start)
  570. endprog = _compile(endpats[initial] or
  571. endpats[token[1]] or
  572. endpats[token[2]])
  573. contstr, needcont = line[start:], 1
  574. contline = line
  575. break
  576. else: # ordinary string
  577. yield TokenInfo(STRING, token, spos, epos, line)
  578. elif initial.isidentifier(): # ordinary name
  579. if token in ('async', 'await'):
  580. if async_def:
  581. yield TokenInfo(
  582. ASYNC if token == 'async' else AWAIT,
  583. token, spos, epos, line)
  584. continue
  585. tok = TokenInfo(NAME, token, spos, epos, line)
  586. if token == 'async' and not stashed:
  587. stashed = tok
  588. continue
  589. if token == 'def':
  590. if (stashed
  591. and stashed.type == NAME
  592. and stashed.string == 'async'):
  593. async_def = True
  594. async_def_indent = indents[-1]
  595. yield TokenInfo(ASYNC, stashed.string,
  596. stashed.start, stashed.end,
  597. stashed.line)
  598. stashed = None
  599. if stashed:
  600. yield stashed
  601. stashed = None
  602. yield tok
  603. elif initial == '\\': # continued stmt
  604. continued = 1
  605. else:
  606. if initial in '([{':
  607. parenlev += 1
  608. elif initial in ')]}':
  609. parenlev -= 1
  610. if stashed:
  611. yield stashed
  612. stashed = None
  613. yield TokenInfo(OP, token, spos, epos, line)
  614. else:
  615. yield TokenInfo(ERRORTOKEN, line[pos],
  616. (lnum, pos), (lnum, pos+1), line)
  617. pos += 1
  618. if stashed:
  619. yield stashed
  620. stashed = None
  621. for indent in indents[1:]: # pop remaining indent levels
  622. yield TokenInfo(DEDENT, '', (lnum, 0), (lnum, 0), '')
  623. yield TokenInfo(ENDMARKER, '', (lnum, 0), (lnum, 0), '')
  624. # An undocumented, backwards compatible, API for all the places in the standard
  625. # library that expect to be able to use tokenize with strings
  626. def generate_tokens(readline):
  627. return _tokenize(readline, None)
  628. def main():
  629. import argparse
  630. # Helper error handling routines
  631. def perror(message):
  632. print(message, file=sys.stderr)
  633. def error(message, filename=None, location=None):
  634. if location:
  635. args = (filename,) + location + (message,)
  636. perror("%s:%d:%d: error: %s" % args)
  637. elif filename:
  638. perror("%s: error: %s" % (filename, message))
  639. else:
  640. perror("error: %s" % message)
  641. sys.exit(1)
  642. # Parse the arguments and options
  643. parser = argparse.ArgumentParser(prog='python -m tokenize')
  644. parser.add_argument(dest='filename', nargs='?',
  645. metavar='filename.py',
  646. help='the file to tokenize; defaults to stdin')
  647. parser.add_argument('-e', '--exact', dest='exact', action='store_true',
  648. help='display token names using the exact type')
  649. args = parser.parse_args()
  650. try:
  651. # Tokenize the input
  652. if args.filename:
  653. filename = args.filename
  654. with _builtin_open(filename, 'rb') as f:
  655. tokens = list(tokenize(f.readline))
  656. else:
  657. filename = "<stdin>"
  658. tokens = _tokenize(sys.stdin.readline, None)
  659. # Output the tokenization
  660. for token in tokens:
  661. token_type = token.type
  662. if args.exact:
  663. token_type = token.exact_type
  664. token_range = "%d,%d-%d,%d:" % (token.start + token.end)
  665. print("%-20s%-15s%-15r" %
  666. (token_range, tok_name[token_type], token.string))
  667. except IndentationError as err:
  668. line, column = err.args[1][1:3]
  669. error(err.args[0], filename, (line, column))
  670. except TokenError as err:
  671. line, column = err.args[1]
  672. error(err.args[0], filename, (line, column))
  673. except SyntaxError as err:
  674. error(err, filename)
  675. except OSError as err:
  676. error(err)
  677. except KeyboardInterrupt:
  678. print("interrupted\n")
  679. except Exception as err:
  680. perror("unexpected error: %s" % err)
  681. raise
  682. if __name__ == "__main__":
  683. main()