blob: 742abd19922bb11416745672141db9286f82e021 [file] [log] [blame]
Guido van Rossumb51eaa11997-03-07 00:21:55 +00001"""Tokenization help for Python programs.
Guido van Rossum4d8e8591992-01-01 19:34:47 +00002
Florent Xicluna43e4ea12010-09-03 19:54:02 +00003tokenize(readline) is a generator that breaks a stream of bytes into
4Python tokens. It decodes the bytes according to PEP-0263 for
5determining source file encoding.
Trent Nelson428de652008-03-18 22:41:35 +00006
Florent Xicluna43e4ea12010-09-03 19:54:02 +00007It accepts a readline-like method which is called repeatedly to get the
8next line of input (or b"" for EOF). It generates 5-tuples with these
9members:
Tim Peters4efb6e92001-06-29 23:51:08 +000010
11 the token type (see token.py)
12 the token (a string)
13 the starting (row, column) indices of the token (a 2-tuple of ints)
14 the ending (row, column) indices of the token (a 2-tuple of ints)
15 the original line (string)
16
17It is designed to match the working of the Python tokenizer exactly, except
18that it produces COMMENT tokens for comments and gives type OP for all
Florent Xicluna43e4ea12010-09-03 19:54:02 +000019operators. Additionally, all token lists start with an ENCODING token
20which tells you which encoding was used to decode the bytes stream.
21"""
Guido van Rossumb51eaa11997-03-07 00:21:55 +000022
Ka-Ping Yee244c5932001-03-01 13:56:40 +000023__author__ = 'Ka-Ping Yee <ping@lfw.org>'
Trent Nelson428de652008-03-18 22:41:35 +000024__credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
25 'Skip Montanaro, Raymond Hettinger, Trent Nelson, '
26 'Michael Foord')
Brett Cannonf3042782011-02-22 03:25:12 +000027import builtins
Benjamin Peterson433f32c2008-12-12 01:25:05 +000028from codecs import lookup, BOM_UTF8
Raymond Hettinger3fb79c72010-09-09 07:15:18 +000029import collections
Victor Stinner58c07522010-11-09 01:08:59 +000030from io import TextIOWrapper
Terry Jan Reedy5b8d2c32014-02-17 23:12:16 -050031from itertools import chain
32import re
33import sys
34from token import *
35
Serhiy Storchakadafea852013-09-16 23:51:56 +030036cookie_re = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)', re.ASCII)
Serhiy Storchaka768c16c2014-01-09 18:36:09 +020037blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII)
Guido van Rossum4d8e8591992-01-01 19:34:47 +000038
Skip Montanaro40fc1602001-03-01 04:27:19 +000039import token
Alexander Belopolskyb9d10d02010-11-11 14:07:41 +000040__all__ = token.__all__ + ["COMMENT", "tokenize", "detect_encoding",
41 "NL", "untokenize", "ENCODING", "TokenInfo"]
Skip Montanaro40fc1602001-03-01 04:27:19 +000042del token
43
Guido van Rossum1aec3231997-04-08 14:24:39 +000044COMMENT = N_TOKENS
45tok_name[COMMENT] = 'COMMENT'
Guido van Rossuma90c78b1998-04-03 16:05:38 +000046NL = N_TOKENS + 1
47tok_name[NL] = 'NL'
Trent Nelson428de652008-03-18 22:41:35 +000048ENCODING = N_TOKENS + 2
49tok_name[ENCODING] = 'ENCODING'
50N_TOKENS += 3
Meador Inge00c7f852012-01-19 00:44:45 -060051EXACT_TOKEN_TYPES = {
52 '(': LPAR,
53 ')': RPAR,
54 '[': LSQB,
55 ']': RSQB,
56 ':': COLON,
57 ',': COMMA,
58 ';': SEMI,
59 '+': PLUS,
60 '-': MINUS,
61 '*': STAR,
62 '/': SLASH,
63 '|': VBAR,
64 '&': AMPER,
65 '<': LESS,
66 '>': GREATER,
67 '=': EQUAL,
68 '.': DOT,
69 '%': PERCENT,
70 '{': LBRACE,
71 '}': RBRACE,
72 '==': EQEQUAL,
73 '!=': NOTEQUAL,
74 '<=': LESSEQUAL,
75 '>=': GREATEREQUAL,
76 '~': TILDE,
77 '^': CIRCUMFLEX,
78 '<<': LEFTSHIFT,
79 '>>': RIGHTSHIFT,
80 '**': DOUBLESTAR,
81 '+=': PLUSEQUAL,
82 '-=': MINEQUAL,
83 '*=': STAREQUAL,
84 '/=': SLASHEQUAL,
85 '%=': PERCENTEQUAL,
86 '&=': AMPEREQUAL,
87 '|=': VBAREQUAL,
88 '^=': CIRCUMFLEXEQUAL,
89 '<<=': LEFTSHIFTEQUAL,
90 '>>=': RIGHTSHIFTEQUAL,
91 '**=': DOUBLESTAREQUAL,
92 '//': DOUBLESLASH,
93 '//=': DOUBLESLASHEQUAL,
Benjamin Petersond51374e2014-04-09 23:55:56 -040094 '@': AT,
95 '@=': ATEQUAL,
Meador Inge00c7f852012-01-19 00:44:45 -060096}
Guido van Rossum1aec3231997-04-08 14:24:39 +000097
Raymond Hettinger3fb79c72010-09-09 07:15:18 +000098class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
Raymond Hettingeraa17a7f2009-04-29 14:21:25 +000099 def __repr__(self):
Raymond Hettingera0e79402010-09-09 08:29:05 +0000100 annotated_type = '%d (%s)' % (self.type, tok_name[self.type])
101 return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' %
102 self._replace(type=annotated_type))
Raymond Hettingeraa17a7f2009-04-29 14:21:25 +0000103
Meador Inge00c7f852012-01-19 00:44:45 -0600104 @property
105 def exact_type(self):
106 if self.type == OP and self.string in EXACT_TOKEN_TYPES:
107 return EXACT_TOKEN_TYPES[self.string]
108 else:
109 return self.type
110
Eric S. Raymondb08b2d32001-02-09 11:10:16 +0000111def group(*choices): return '(' + '|'.join(choices) + ')'
Guido van Rossum68468eb2003-02-27 20:14:51 +0000112def any(*choices): return group(*choices) + '*'
113def maybe(*choices): return group(*choices) + '?'
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000114
Antoine Pitroufd036452008-08-19 17:56:33 +0000115# Note: we use unicode matching for names ("\w") but ascii matching for
116# number literals.
Guido van Rossum3b631771997-10-27 20:44:15 +0000117Whitespace = r'[ \f\t]*'
118Comment = r'#[^\r\n]*'
119Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
Benjamin Peterson33856de2010-08-30 14:41:20 +0000120Name = r'\w+'
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000121
Antoine Pitroufd036452008-08-19 17:56:33 +0000122Hexnumber = r'0[xX][0-9a-fA-F]+'
Georg Brandlfceab5a2008-01-19 20:08:23 +0000123Binnumber = r'0[bB][01]+'
124Octnumber = r'0[oO][0-7]+'
Antoine Pitroufd036452008-08-19 17:56:33 +0000125Decnumber = r'(?:0+|[1-9][0-9]*)'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000126Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
Antoine Pitroufd036452008-08-19 17:56:33 +0000127Exponent = r'[eE][-+]?[0-9]+'
128Pointfloat = group(r'[0-9]+\.[0-9]*', r'\.[0-9]+') + maybe(Exponent)
129Expfloat = r'[0-9]+' + Exponent
Guido van Rossum1aec3231997-04-08 14:24:39 +0000130Floatnumber = group(Pointfloat, Expfloat)
Antoine Pitroufd036452008-08-19 17:56:33 +0000131Imagnumber = group(r'[0-9]+[jJ]', Floatnumber + r'[jJ]')
Guido van Rossum1aec3231997-04-08 14:24:39 +0000132Number = group(Imagnumber, Floatnumber, Intnumber)
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000133
Christian Heimes0b3847d2012-06-20 11:17:58 +0200134StringPrefix = r'(?:[bB][rR]?|[rR][bB]?|[uU])?'
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000135
Tim Petersde495832000-10-07 05:09:39 +0000136# Tail end of ' string.
137Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
138# Tail end of " string.
139Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
140# Tail end of ''' string.
141Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
142# Tail end of """ string.
143Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000144Triple = group(StringPrefix + "'''", StringPrefix + '"""')
Tim Petersde495832000-10-07 05:09:39 +0000145# Single-line ' or " string.
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000146String = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
147 StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000148
Tim Petersde495832000-10-07 05:09:39 +0000149# Because of leftmost-then-longest match semantics, be sure to put the
150# longest operators first (e.g., if = came before ==, == would get
151# recognized as two instances of =).
Guido van Rossumb053cd82006-08-24 03:53:23 +0000152Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=",
Neal Norwitzc1505362006-12-28 06:47:50 +0000153 r"//=?", r"->",
Benjamin Petersond51374e2014-04-09 23:55:56 -0400154 r"[+\-*/%&@|^=<>]=?",
Tim Petersde495832000-10-07 05:09:39 +0000155 r"~")
Thomas Wouterse1519a12000-08-24 21:44:52 +0000156
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000157Bracket = '[][(){}]'
Georg Brandldde00282007-03-18 19:01:53 +0000158Special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]')
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000159Funny = group(Operator, Bracket, Special)
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000160
Guido van Rossum3b631771997-10-27 20:44:15 +0000161PlainToken = group(Number, Funny, String, Name)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000162Token = Ignore + PlainToken
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000163
Tim Petersde495832000-10-07 05:09:39 +0000164# First (or only) line of ' or " string.
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000165ContStr = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
Ka-Ping Yee1ff08b12001-01-15 22:04:30 +0000166 group("'", r'\\\r?\n'),
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000167 StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
Ka-Ping Yee1ff08b12001-01-15 22:04:30 +0000168 group('"', r'\\\r?\n'))
Ezio Melotti2cc3b4b2012-11-03 17:38:43 +0200169PseudoExtras = group(r'\\\r?\n|\Z', Comment, Triple)
Guido van Rossum3b631771997-10-27 20:44:15 +0000170PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000171
Benjamin Peterson33856de2010-08-30 14:41:20 +0000172def _compile(expr):
173 return re.compile(expr, re.UNICODE)
174
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200175endpats = {"'": Single, '"': Double,
176 "'''": Single3, '"""': Double3,
177 "r'''": Single3, 'r"""': Double3,
178 "b'''": Single3, 'b"""': Double3,
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200179 "R'''": Single3, 'R"""': Double3,
180 "B'''": Single3, 'B"""': Double3,
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000181 "br'''": Single3, 'br"""': Double3,
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200182 "bR'''": Single3, 'bR"""': Double3,
183 "Br'''": Single3, 'Br"""': Double3,
184 "BR'''": Single3, 'BR"""': Double3,
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000185 "rb'''": Single3, 'rb"""': Double3,
186 "Rb'''": Single3, 'Rb"""': Double3,
187 "rB'''": Single3, 'rB"""': Double3,
188 "RB'''": Single3, 'RB"""': Double3,
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000189 "u'''": Single3, 'u"""': Double3,
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000190 "R'''": Single3, 'R"""': Double3,
191 "U'''": Single3, 'U"""': Double3,
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000192 'r': None, 'R': None, 'b': None, 'B': None,
193 'u': None, 'U': None}
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000194
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000195triple_quoted = {}
196for t in ("'''", '"""',
197 "r'''", 'r"""', "R'''", 'R"""',
Guido van Rossum4fe72f92007-11-12 17:40:10 +0000198 "b'''", 'b"""', "B'''", 'B"""',
199 "br'''", 'br"""', "Br'''", 'Br"""',
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000200 "bR'''", 'bR"""', "BR'''", 'BR"""',
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000201 "rb'''", 'rb"""', "rB'''", 'rB"""',
202 "Rb'''", 'Rb"""', "RB'''", 'RB"""',
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000203 "u'''", 'u"""', "U'''", 'U"""',
Christian Heimes0b3847d2012-06-20 11:17:58 +0200204 ):
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000205 triple_quoted[t] = t
206single_quoted = {}
207for t in ("'", '"',
208 "r'", 'r"', "R'", 'R"',
Guido van Rossum4fe72f92007-11-12 17:40:10 +0000209 "b'", 'b"', "B'", 'B"',
210 "br'", 'br"', "Br'", 'Br"',
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000211 "bR'", 'bR"', "BR'", 'BR"' ,
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000212 "rb'", 'rb"', "rB'", 'rB"',
213 "Rb'", 'Rb"', "RB'", 'RB"' ,
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000214 "u'", 'u"', "U'", 'U"',
Christian Heimes0b3847d2012-06-20 11:17:58 +0200215 ):
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000216 single_quoted[t] = t
217
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000218tabsize = 8
Fred Drake9b8d8012000-08-17 04:45:13 +0000219
Ka-Ping Yee28c62bb2001-03-23 05:22:49 +0000220class TokenError(Exception): pass
221
222class StopTokenizing(Exception): pass
Fred Drake9b8d8012000-08-17 04:45:13 +0000223
Tim Peters5ca576e2001-06-18 22:08:13 +0000224
Thomas Wouters89f507f2006-12-13 04:49:30 +0000225class Untokenizer:
226
227 def __init__(self):
228 self.tokens = []
229 self.prev_row = 1
230 self.prev_col = 0
Trent Nelson428de652008-03-18 22:41:35 +0000231 self.encoding = None
Thomas Wouters89f507f2006-12-13 04:49:30 +0000232
233 def add_whitespace(self, start):
234 row, col = start
Terry Jan Reedy5e6db312014-02-17 16:45:48 -0500235 if row < self.prev_row or row == self.prev_row and col < self.prev_col:
236 raise ValueError("start ({},{}) precedes previous end ({},{})"
237 .format(row, col, self.prev_row, self.prev_col))
Terry Jan Reedy9dc3a362014-02-23 23:33:08 -0500238 row_offset = row - self.prev_row
Terry Jan Reedyf106f8f2014-02-23 23:39:57 -0500239 if row_offset:
Terry Jan Reedy9dc3a362014-02-23 23:33:08 -0500240 self.tokens.append("\\\n" * row_offset)
241 self.prev_col = 0
Thomas Wouters89f507f2006-12-13 04:49:30 +0000242 col_offset = col - self.prev_col
243 if col_offset:
244 self.tokens.append(" " * col_offset)
245
246 def untokenize(self, iterable):
Terry Jan Reedy5b8d2c32014-02-17 23:12:16 -0500247 it = iter(iterable)
248 for t in it:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000249 if len(t) == 2:
Terry Jan Reedy5b8d2c32014-02-17 23:12:16 -0500250 self.compat(t, it)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000251 break
252 tok_type, token, start, end, line = t
Trent Nelson428de652008-03-18 22:41:35 +0000253 if tok_type == ENCODING:
254 self.encoding = token
255 continue
Terry Jan Reedy9dc3a362014-02-23 23:33:08 -0500256 if tok_type == ENDMARKER:
257 break
Thomas Wouters89f507f2006-12-13 04:49:30 +0000258 self.add_whitespace(start)
259 self.tokens.append(token)
260 self.prev_row, self.prev_col = end
261 if tok_type in (NEWLINE, NL):
262 self.prev_row += 1
263 self.prev_col = 0
264 return "".join(self.tokens)
265
266 def compat(self, token, iterable):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000267 indents = []
268 toks_append = self.tokens.append
Terry Jan Reedy5b8d2c32014-02-17 23:12:16 -0500269 startline = token[0] in (NEWLINE, NL)
Christian Heimesba4af492008-03-28 00:55:15 +0000270 prevstring = False
Terry Jan Reedy5b8d2c32014-02-17 23:12:16 -0500271
272 for tok in chain([token], iterable):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000273 toknum, tokval = tok[:2]
Trent Nelson428de652008-03-18 22:41:35 +0000274 if toknum == ENCODING:
275 self.encoding = tokval
276 continue
Thomas Wouters89f507f2006-12-13 04:49:30 +0000277
278 if toknum in (NAME, NUMBER):
279 tokval += ' '
280
Christian Heimesba4af492008-03-28 00:55:15 +0000281 # Insert a space between two consecutive strings
282 if toknum == STRING:
283 if prevstring:
284 tokval = ' ' + tokval
285 prevstring = True
286 else:
287 prevstring = False
288
Thomas Wouters89f507f2006-12-13 04:49:30 +0000289 if toknum == INDENT:
290 indents.append(tokval)
291 continue
292 elif toknum == DEDENT:
293 indents.pop()
294 continue
295 elif toknum in (NEWLINE, NL):
296 startline = True
297 elif startline and indents:
298 toks_append(indents[-1])
299 startline = False
300 toks_append(tokval)
Raymond Hettinger68c04532005-06-10 11:05:19 +0000301
Trent Nelson428de652008-03-18 22:41:35 +0000302
Raymond Hettinger68c04532005-06-10 11:05:19 +0000303def untokenize(iterable):
304 """Transform tokens back into Python source code.
Trent Nelson428de652008-03-18 22:41:35 +0000305 It returns a bytes object, encoded using the ENCODING
306 token, which is the first token sequence output by tokenize.
Raymond Hettinger68c04532005-06-10 11:05:19 +0000307
308 Each element returned by the iterable must be a token sequence
Thomas Wouters89f507f2006-12-13 04:49:30 +0000309 with at least two elements, a token number and token value. If
310 only two tokens are passed, the resulting output is poor.
Raymond Hettinger68c04532005-06-10 11:05:19 +0000311
Thomas Wouters89f507f2006-12-13 04:49:30 +0000312 Round-trip invariant for full input:
313 Untokenized source will match input source exactly
314
315 Round-trip invariant for limited intput:
Trent Nelson428de652008-03-18 22:41:35 +0000316 # Output bytes will tokenize the back to the input
317 t1 = [tok[:2] for tok in tokenize(f.readline)]
Raymond Hettinger68c04532005-06-10 11:05:19 +0000318 newcode = untokenize(t1)
Trent Nelson428de652008-03-18 22:41:35 +0000319 readline = BytesIO(newcode).readline
320 t2 = [tok[:2] for tok in tokenize(readline)]
Raymond Hettinger68c04532005-06-10 11:05:19 +0000321 assert t1 == t2
322 """
Thomas Wouters89f507f2006-12-13 04:49:30 +0000323 ut = Untokenizer()
Trent Nelson428de652008-03-18 22:41:35 +0000324 out = ut.untokenize(iterable)
325 if ut.encoding is not None:
326 out = out.encode(ut.encoding)
327 return out
Raymond Hettinger68c04532005-06-10 11:05:19 +0000328
Trent Nelson428de652008-03-18 22:41:35 +0000329
Benjamin Petersond3afada2009-10-09 21:43:09 +0000330def _get_normal_name(orig_enc):
331 """Imitates get_normal_name in tokenizer.c."""
332 # Only care about the first 12 characters.
333 enc = orig_enc[:12].lower().replace("_", "-")
334 if enc == "utf-8" or enc.startswith("utf-8-"):
335 return "utf-8"
336 if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
337 enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
338 return "iso-8859-1"
339 return orig_enc
340
Trent Nelson428de652008-03-18 22:41:35 +0000341def detect_encoding(readline):
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000342 """
Trent Nelson428de652008-03-18 22:41:35 +0000343 The detect_encoding() function is used to detect the encoding that should
Ezio Melotti4bcc7962013-11-25 05:14:51 +0200344 be used to decode a Python source file. It requires one argument, readline,
Trent Nelson428de652008-03-18 22:41:35 +0000345 in the same way as the tokenize() generator.
346
347 It will call readline a maximum of twice, and return the encoding used
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000348 (as a string) and a list of any lines (left as bytes) it has read in.
Trent Nelson428de652008-03-18 22:41:35 +0000349
350 It detects the encoding from the presence of a utf-8 bom or an encoding
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000351 cookie as specified in pep-0263. If both a bom and a cookie are present,
352 but disagree, a SyntaxError will be raised. If the encoding cookie is an
353 invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
Benjamin Peterson689a5582010-03-18 22:29:52 +0000354 'utf-8-sig' is returned.
Trent Nelson428de652008-03-18 22:41:35 +0000355
356 If no encoding is specified, then the default of 'utf-8' will be returned.
357 """
Brett Cannonc33f3f22012-04-20 13:23:54 -0400358 try:
359 filename = readline.__self__.name
360 except AttributeError:
361 filename = None
Trent Nelson428de652008-03-18 22:41:35 +0000362 bom_found = False
363 encoding = None
Benjamin Peterson689a5582010-03-18 22:29:52 +0000364 default = 'utf-8'
Trent Nelson428de652008-03-18 22:41:35 +0000365 def read_or_stop():
366 try:
367 return readline()
368 except StopIteration:
369 return b''
370
371 def find_cookie(line):
372 try:
Martin v. Löwis63674f42012-04-20 14:36:47 +0200373 # Decode as UTF-8. Either the line is an encoding declaration,
374 # in which case it should be pure ASCII, or it must be UTF-8
375 # per default encoding.
376 line_string = line.decode('utf-8')
Trent Nelson428de652008-03-18 22:41:35 +0000377 except UnicodeDecodeError:
Brett Cannonc33f3f22012-04-20 13:23:54 -0400378 msg = "invalid or missing encoding declaration"
379 if filename is not None:
380 msg = '{} for {!r}'.format(msg, filename)
381 raise SyntaxError(msg)
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000382
Serhiy Storchakadafea852013-09-16 23:51:56 +0300383 match = cookie_re.match(line_string)
384 if not match:
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000385 return None
Serhiy Storchakadafea852013-09-16 23:51:56 +0300386 encoding = _get_normal_name(match.group(1))
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000387 try:
388 codec = lookup(encoding)
389 except LookupError:
390 # This behaviour mimics the Python interpreter
Brett Cannonc33f3f22012-04-20 13:23:54 -0400391 if filename is None:
392 msg = "unknown encoding: " + encoding
393 else:
394 msg = "unknown encoding for {!r}: {}".format(filename,
395 encoding)
396 raise SyntaxError(msg)
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000397
Benjamin Peterson1613ed82010-03-18 22:34:15 +0000398 if bom_found:
Florent Xicluna11f0b412012-07-07 12:13:35 +0200399 if encoding != 'utf-8':
Benjamin Peterson1613ed82010-03-18 22:34:15 +0000400 # This behaviour mimics the Python interpreter
Brett Cannonc33f3f22012-04-20 13:23:54 -0400401 if filename is None:
402 msg = 'encoding problem: utf-8'
403 else:
404 msg = 'encoding problem for {!r}: utf-8'.format(filename)
405 raise SyntaxError(msg)
Benjamin Peterson1613ed82010-03-18 22:34:15 +0000406 encoding += '-sig'
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000407 return encoding
Trent Nelson428de652008-03-18 22:41:35 +0000408
409 first = read_or_stop()
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000410 if first.startswith(BOM_UTF8):
Trent Nelson428de652008-03-18 22:41:35 +0000411 bom_found = True
412 first = first[3:]
Benjamin Peterson689a5582010-03-18 22:29:52 +0000413 default = 'utf-8-sig'
Trent Nelson428de652008-03-18 22:41:35 +0000414 if not first:
Benjamin Peterson689a5582010-03-18 22:29:52 +0000415 return default, []
Trent Nelson428de652008-03-18 22:41:35 +0000416
417 encoding = find_cookie(first)
418 if encoding:
419 return encoding, [first]
Serhiy Storchaka768c16c2014-01-09 18:36:09 +0200420 if not blank_re.match(first):
421 return default, [first]
Trent Nelson428de652008-03-18 22:41:35 +0000422
423 second = read_or_stop()
424 if not second:
Benjamin Peterson689a5582010-03-18 22:29:52 +0000425 return default, [first]
Trent Nelson428de652008-03-18 22:41:35 +0000426
427 encoding = find_cookie(second)
428 if encoding:
429 return encoding, [first, second]
430
Benjamin Peterson689a5582010-03-18 22:29:52 +0000431 return default, [first, second]
Trent Nelson428de652008-03-18 22:41:35 +0000432
433
Victor Stinner58c07522010-11-09 01:08:59 +0000434def open(filename):
435 """Open a file in read only mode using the encoding detected by
436 detect_encoding().
437 """
Brett Cannonf3042782011-02-22 03:25:12 +0000438 buffer = builtins.open(filename, 'rb')
Victor Stinner58c07522010-11-09 01:08:59 +0000439 encoding, lines = detect_encoding(buffer.readline)
440 buffer.seek(0)
441 text = TextIOWrapper(buffer, encoding, line_buffering=True)
442 text.mode = 'r'
443 return text
444
445
Trent Nelson428de652008-03-18 22:41:35 +0000446def tokenize(readline):
447 """
448 The tokenize() generator requires one argment, readline, which
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000449 must be a callable object which provides the same interface as the
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000450 readline() method of built-in file objects. Each call to the function
Trent Nelson428de652008-03-18 22:41:35 +0000451 should return one line of input as bytes. Alternately, readline
Raymond Hettinger68c04532005-06-10 11:05:19 +0000452 can be a callable function terminating with StopIteration:
Trent Nelson428de652008-03-18 22:41:35 +0000453 readline = open(myfile, 'rb').__next__ # Example of alternate readline
Tim Peters8ac14952002-05-23 15:15:30 +0000454
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000455 The generator produces 5-tuples with these members: the token type; the
456 token string; a 2-tuple (srow, scol) of ints specifying the row and
457 column where the token begins in the source; a 2-tuple (erow, ecol) of
458 ints specifying the row and column where the token ends in the source;
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000459 and the line on which the token was found. The line passed is the
Tim Peters8ac14952002-05-23 15:15:30 +0000460 logical line; continuation lines are included.
Trent Nelson428de652008-03-18 22:41:35 +0000461
462 The first token sequence will always be an ENCODING token
463 which tells you which encoding was used to decode the bytes stream.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000464 """
Benjamin Peterson21db77e2009-11-14 16:27:26 +0000465 # This import is here to avoid problems when the itertools module is not
466 # built yet and tokenize is imported.
Benjamin Peterson81dd8b92009-11-14 18:09:17 +0000467 from itertools import chain, repeat
Trent Nelson428de652008-03-18 22:41:35 +0000468 encoding, consumed = detect_encoding(readline)
Benjamin Peterson81dd8b92009-11-14 18:09:17 +0000469 rl_gen = iter(readline, b"")
470 empty = repeat(b"")
471 return _tokenize(chain(consumed, rl_gen, empty).__next__, encoding)
Trent Nelson428de652008-03-18 22:41:35 +0000472
473
474def _tokenize(readline, encoding):
Guido van Rossum1aec3231997-04-08 14:24:39 +0000475 lnum = parenlev = continued = 0
Benjamin Peterson33856de2010-08-30 14:41:20 +0000476 numchars = '0123456789'
Guido van Rossumde655271997-04-09 17:15:54 +0000477 contstr, needcont = '', 0
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000478 contline = None
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000479 indents = [0]
Guido van Rossum1aec3231997-04-08 14:24:39 +0000480
Trent Nelson428de652008-03-18 22:41:35 +0000481 if encoding is not None:
Benjamin Peterson689a5582010-03-18 22:29:52 +0000482 if encoding == "utf-8-sig":
483 # BOM will already have been stripped.
484 encoding = "utf-8"
Raymond Hettingera48db392009-04-29 00:34:27 +0000485 yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '')
Benjamin Peterson0fe14382008-06-05 23:07:42 +0000486 while True: # loop over lines in stream
Raymond Hettinger68c04532005-06-10 11:05:19 +0000487 try:
488 line = readline()
489 except StopIteration:
Trent Nelson428de652008-03-18 22:41:35 +0000490 line = b''
491
492 if encoding is not None:
493 line = line.decode(encoding)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000494 lnum += 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000495 pos, max = 0, len(line)
496
497 if contstr: # continued string
Guido van Rossumde655271997-04-09 17:15:54 +0000498 if not line:
Collin Winterce36ad82007-08-30 01:19:48 +0000499 raise TokenError("EOF in multi-line string", strstart)
Guido van Rossum3b631771997-10-27 20:44:15 +0000500 endmatch = endprog.match(line)
501 if endmatch:
502 pos = end = endmatch.end(0)
Raymond Hettingera48db392009-04-29 00:34:27 +0000503 yield TokenInfo(STRING, contstr + line[:end],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000504 strstart, (lnum, end), contline + line)
Guido van Rossumde655271997-04-09 17:15:54 +0000505 contstr, needcont = '', 0
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000506 contline = None
Guido van Rossumde655271997-04-09 17:15:54 +0000507 elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
Raymond Hettingera48db392009-04-29 00:34:27 +0000508 yield TokenInfo(ERRORTOKEN, contstr + line,
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000509 strstart, (lnum, len(line)), contline)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000510 contstr = ''
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000511 contline = None
Guido van Rossumde655271997-04-09 17:15:54 +0000512 continue
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000513 else:
514 contstr = contstr + line
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000515 contline = contline + line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000516 continue
517
Guido van Rossum1aec3231997-04-08 14:24:39 +0000518 elif parenlev == 0 and not continued: # new statement
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000519 if not line: break
520 column = 0
Guido van Rossum1aec3231997-04-08 14:24:39 +0000521 while pos < max: # measure leading whitespace
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000522 if line[pos] == ' ':
523 column += 1
524 elif line[pos] == '\t':
525 column = (column//tabsize + 1)*tabsize
526 elif line[pos] == '\f':
527 column = 0
528 else:
529 break
530 pos += 1
531 if pos == max:
532 break
Guido van Rossum1aec3231997-04-08 14:24:39 +0000533
534 if line[pos] in '#\r\n': # skip comments or blank lines
Thomas Wouters89f507f2006-12-13 04:49:30 +0000535 if line[pos] == '#':
536 comment_token = line[pos:].rstrip('\r\n')
537 nl_pos = pos + len(comment_token)
Raymond Hettingera48db392009-04-29 00:34:27 +0000538 yield TokenInfo(COMMENT, comment_token,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000539 (lnum, pos), (lnum, pos + len(comment_token)), line)
Raymond Hettingera48db392009-04-29 00:34:27 +0000540 yield TokenInfo(NL, line[nl_pos:],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000541 (lnum, nl_pos), (lnum, len(line)), line)
542 else:
Raymond Hettingera48db392009-04-29 00:34:27 +0000543 yield TokenInfo((NL, COMMENT)[line[pos] == '#'], line[pos:],
Guido van Rossum1aec3231997-04-08 14:24:39 +0000544 (lnum, pos), (lnum, len(line)), line)
545 continue
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000546
547 if column > indents[-1]: # count indents or dedents
548 indents.append(column)
Raymond Hettingera48db392009-04-29 00:34:27 +0000549 yield TokenInfo(INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000550 while column < indents[-1]:
Raymond Hettingerda99d1c2005-06-21 07:43:58 +0000551 if column not in indents:
552 raise IndentationError(
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000553 "unindent does not match any outer indentation level",
554 ("<tokenize>", lnum, pos, line))
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000555 indents = indents[:-1]
Raymond Hettingera48db392009-04-29 00:34:27 +0000556 yield TokenInfo(DEDENT, '', (lnum, pos), (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000557
558 else: # continued statement
Guido van Rossumde655271997-04-09 17:15:54 +0000559 if not line:
Collin Winterce36ad82007-08-30 01:19:48 +0000560 raise TokenError("EOF in multi-line statement", (lnum, 0))
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000561 continued = 0
562
563 while pos < max:
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200564 pseudomatch = _compile(PseudoToken).match(line, pos)
Guido van Rossum3b631771997-10-27 20:44:15 +0000565 if pseudomatch: # scan for tokens
566 start, end = pseudomatch.span(1)
Guido van Rossumde655271997-04-09 17:15:54 +0000567 spos, epos, pos = (lnum, start), (lnum, end), end
Ezio Melotti2cc3b4b2012-11-03 17:38:43 +0200568 if start == end:
569 continue
Guido van Rossum1aec3231997-04-08 14:24:39 +0000570 token, initial = line[start:end], line[start]
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000571
Georg Brandldde00282007-03-18 19:01:53 +0000572 if (initial in numchars or # ordinary number
573 (initial == '.' and token != '.' and token != '...')):
Raymond Hettingera48db392009-04-29 00:34:27 +0000574 yield TokenInfo(NUMBER, token, spos, epos, line)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000575 elif initial in '\r\n':
Raymond Hettingera48db392009-04-29 00:34:27 +0000576 yield TokenInfo(NL if parenlev > 0 else NEWLINE,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000577 token, spos, epos, line)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000578 elif initial == '#':
Thomas Wouters89f507f2006-12-13 04:49:30 +0000579 assert not token.endswith("\n")
Raymond Hettingera48db392009-04-29 00:34:27 +0000580 yield TokenInfo(COMMENT, token, spos, epos, line)
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000581 elif token in triple_quoted:
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200582 endprog = _compile(endpats[token])
Guido van Rossum3b631771997-10-27 20:44:15 +0000583 endmatch = endprog.match(line, pos)
584 if endmatch: # all on one line
585 pos = endmatch.end(0)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000586 token = line[start:pos]
Raymond Hettingera48db392009-04-29 00:34:27 +0000587 yield TokenInfo(STRING, token, spos, (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000588 else:
Guido van Rossum1aec3231997-04-08 14:24:39 +0000589 strstart = (lnum, start) # multiple lines
590 contstr = line[start:]
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000591 contline = line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000592 break
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000593 elif initial in single_quoted or \
594 token[:2] in single_quoted or \
595 token[:3] in single_quoted:
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000596 if token[-1] == '\n': # continued string
Guido van Rossum1aec3231997-04-08 14:24:39 +0000597 strstart = (lnum, start)
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200598 endprog = _compile(endpats[initial] or
599 endpats[token[1]] or
600 endpats[token[2]])
Guido van Rossumde655271997-04-09 17:15:54 +0000601 contstr, needcont = line[start:], 1
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000602 contline = line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000603 break
604 else: # ordinary string
Raymond Hettingera48db392009-04-29 00:34:27 +0000605 yield TokenInfo(STRING, token, spos, epos, line)
Benjamin Peterson33856de2010-08-30 14:41:20 +0000606 elif initial.isidentifier(): # ordinary name
Raymond Hettingera48db392009-04-29 00:34:27 +0000607 yield TokenInfo(NAME, token, spos, epos, line)
Guido van Rossum3b631771997-10-27 20:44:15 +0000608 elif initial == '\\': # continued stmt
609 continued = 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000610 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000611 if initial in '([{':
612 parenlev += 1
613 elif initial in ')]}':
614 parenlev -= 1
Raymond Hettingera48db392009-04-29 00:34:27 +0000615 yield TokenInfo(OP, token, spos, epos, line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000616 else:
Raymond Hettingera48db392009-04-29 00:34:27 +0000617 yield TokenInfo(ERRORTOKEN, line[pos],
Guido van Rossumde655271997-04-09 17:15:54 +0000618 (lnum, pos), (lnum, pos+1), line)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000619 pos += 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000620
621 for indent in indents[1:]: # pop remaining indent levels
Raymond Hettingera48db392009-04-29 00:34:27 +0000622 yield TokenInfo(DEDENT, '', (lnum, 0), (lnum, 0), '')
623 yield TokenInfo(ENDMARKER, '', (lnum, 0), (lnum, 0), '')
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000624
Trent Nelson428de652008-03-18 22:41:35 +0000625
626# An undocumented, backwards compatible, API for all the places in the standard
627# library that expect to be able to use tokenize with strings
628def generate_tokens(readline):
629 return _tokenize(readline, None)
Raymond Hettinger6c60d092010-09-09 04:32:39 +0000630
Meador Inge14c0f032011-10-07 08:53:38 -0500631def main():
632 import argparse
633
634 # Helper error handling routines
635 def perror(message):
636 print(message, file=sys.stderr)
637
638 def error(message, filename=None, location=None):
639 if location:
640 args = (filename,) + location + (message,)
641 perror("%s:%d:%d: error: %s" % args)
642 elif filename:
643 perror("%s: error: %s" % (filename, message))
644 else:
645 perror("error: %s" % message)
646 sys.exit(1)
647
648 # Parse the arguments and options
649 parser = argparse.ArgumentParser(prog='python -m tokenize')
650 parser.add_argument(dest='filename', nargs='?',
651 metavar='filename.py',
652 help='the file to tokenize; defaults to stdin')
Meador Inge00c7f852012-01-19 00:44:45 -0600653 parser.add_argument('-e', '--exact', dest='exact', action='store_true',
654 help='display token names using the exact type')
Meador Inge14c0f032011-10-07 08:53:38 -0500655 args = parser.parse_args()
656
657 try:
658 # Tokenize the input
659 if args.filename:
660 filename = args.filename
661 with builtins.open(filename, 'rb') as f:
662 tokens = list(tokenize(f.readline))
663 else:
664 filename = "<stdin>"
665 tokens = _tokenize(sys.stdin.readline, None)
666
667 # Output the tokenization
668 for token in tokens:
Meador Inge00c7f852012-01-19 00:44:45 -0600669 token_type = token.type
670 if args.exact:
671 token_type = token.exact_type
Meador Inge14c0f032011-10-07 08:53:38 -0500672 token_range = "%d,%d-%d,%d:" % (token.start + token.end)
673 print("%-20s%-15s%-15r" %
Meador Inge00c7f852012-01-19 00:44:45 -0600674 (token_range, tok_name[token_type], token.string))
Meador Inge14c0f032011-10-07 08:53:38 -0500675 except IndentationError as err:
676 line, column = err.args[1][1:3]
677 error(err.args[0], filename, (line, column))
678 except TokenError as err:
679 line, column = err.args[1]
680 error(err.args[0], filename, (line, column))
681 except SyntaxError as err:
682 error(err, filename)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200683 except OSError as err:
Meador Inge14c0f032011-10-07 08:53:38 -0500684 error(err)
685 except KeyboardInterrupt:
686 print("interrupted\n")
687 except Exception as err:
688 perror("unexpected error: %s" % err)
689 raise
690
Raymond Hettinger6c60d092010-09-09 04:32:39 +0000691if __name__ == "__main__":
Meador Inge14c0f032011-10-07 08:53:38 -0500692 main()