blob: 7356a88b2172c607c097e167430d12fd510d1d79 [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,
94 '@': AT
95}
Guido van Rossum1aec3231997-04-08 14:24:39 +000096
Raymond Hettinger3fb79c72010-09-09 07:15:18 +000097class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
Raymond Hettingeraa17a7f2009-04-29 14:21:25 +000098 def __repr__(self):
Raymond Hettingera0e79402010-09-09 08:29:05 +000099 annotated_type = '%d (%s)' % (self.type, tok_name[self.type])
100 return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' %
101 self._replace(type=annotated_type))
Raymond Hettingeraa17a7f2009-04-29 14:21:25 +0000102
Meador Inge00c7f852012-01-19 00:44:45 -0600103 @property
104 def exact_type(self):
105 if self.type == OP and self.string in EXACT_TOKEN_TYPES:
106 return EXACT_TOKEN_TYPES[self.string]
107 else:
108 return self.type
109
Eric S. Raymondb08b2d32001-02-09 11:10:16 +0000110def group(*choices): return '(' + '|'.join(choices) + ')'
Guido van Rossum68468eb2003-02-27 20:14:51 +0000111def any(*choices): return group(*choices) + '*'
112def maybe(*choices): return group(*choices) + '?'
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000113
Antoine Pitroufd036452008-08-19 17:56:33 +0000114# Note: we use unicode matching for names ("\w") but ascii matching for
115# number literals.
Guido van Rossum3b631771997-10-27 20:44:15 +0000116Whitespace = r'[ \f\t]*'
117Comment = r'#[^\r\n]*'
118Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
Benjamin Peterson33856de2010-08-30 14:41:20 +0000119Name = r'\w+'
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000120
Antoine Pitroufd036452008-08-19 17:56:33 +0000121Hexnumber = r'0[xX][0-9a-fA-F]+'
Georg Brandlfceab5a2008-01-19 20:08:23 +0000122Binnumber = r'0[bB][01]+'
123Octnumber = r'0[oO][0-7]+'
Antoine Pitroufd036452008-08-19 17:56:33 +0000124Decnumber = r'(?:0+|[1-9][0-9]*)'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000125Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
Antoine Pitroufd036452008-08-19 17:56:33 +0000126Exponent = r'[eE][-+]?[0-9]+'
127Pointfloat = group(r'[0-9]+\.[0-9]*', r'\.[0-9]+') + maybe(Exponent)
128Expfloat = r'[0-9]+' + Exponent
Guido van Rossum1aec3231997-04-08 14:24:39 +0000129Floatnumber = group(Pointfloat, Expfloat)
Antoine Pitroufd036452008-08-19 17:56:33 +0000130Imagnumber = group(r'[0-9]+[jJ]', Floatnumber + r'[jJ]')
Guido van Rossum1aec3231997-04-08 14:24:39 +0000131Number = group(Imagnumber, Floatnumber, Intnumber)
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000132
Christian Heimes0b3847d2012-06-20 11:17:58 +0200133StringPrefix = r'(?:[bB][rR]?|[rR][bB]?|[uU])?'
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000134
Tim Petersde495832000-10-07 05:09:39 +0000135# Tail end of ' string.
136Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
137# Tail end of " string.
138Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
139# Tail end of ''' string.
140Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
141# Tail end of """ string.
142Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000143Triple = group(StringPrefix + "'''", StringPrefix + '"""')
Tim Petersde495832000-10-07 05:09:39 +0000144# Single-line ' or " string.
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000145String = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
146 StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000147
Tim Petersde495832000-10-07 05:09:39 +0000148# Because of leftmost-then-longest match semantics, be sure to put the
149# longest operators first (e.g., if = came before ==, == would get
150# recognized as two instances of =).
Guido van Rossumb053cd82006-08-24 03:53:23 +0000151Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=",
Neal Norwitzc1505362006-12-28 06:47:50 +0000152 r"//=?", r"->",
Tim Petersde495832000-10-07 05:09:39 +0000153 r"[+\-*/%&|^=<>]=?",
154 r"~")
Thomas Wouterse1519a12000-08-24 21:44:52 +0000155
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000156Bracket = '[][(){}]'
Georg Brandldde00282007-03-18 19:01:53 +0000157Special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]')
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000158Funny = group(Operator, Bracket, Special)
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000159
Guido van Rossum3b631771997-10-27 20:44:15 +0000160PlainToken = group(Number, Funny, String, Name)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000161Token = Ignore + PlainToken
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000162
Tim Petersde495832000-10-07 05:09:39 +0000163# First (or only) line of ' or " string.
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000164ContStr = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
Ka-Ping Yee1ff08b12001-01-15 22:04:30 +0000165 group("'", r'\\\r?\n'),
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000166 StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
Ka-Ping Yee1ff08b12001-01-15 22:04:30 +0000167 group('"', r'\\\r?\n'))
Ezio Melotti2cc3b4b2012-11-03 17:38:43 +0200168PseudoExtras = group(r'\\\r?\n|\Z', Comment, Triple)
Guido van Rossum3b631771997-10-27 20:44:15 +0000169PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000170
Benjamin Peterson33856de2010-08-30 14:41:20 +0000171def _compile(expr):
172 return re.compile(expr, re.UNICODE)
173
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200174endpats = {"'": Single, '"': Double,
175 "'''": Single3, '"""': Double3,
176 "r'''": Single3, 'r"""': Double3,
177 "b'''": Single3, 'b"""': Double3,
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200178 "R'''": Single3, 'R"""': Double3,
179 "B'''": Single3, 'B"""': Double3,
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000180 "br'''": Single3, 'br"""': Double3,
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200181 "bR'''": Single3, 'bR"""': Double3,
182 "Br'''": Single3, 'Br"""': Double3,
183 "BR'''": Single3, 'BR"""': Double3,
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000184 "rb'''": Single3, 'rb"""': Double3,
185 "Rb'''": Single3, 'Rb"""': Double3,
186 "rB'''": Single3, 'rB"""': Double3,
187 "RB'''": Single3, 'RB"""': Double3,
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000188 "u'''": Single3, 'u"""': Double3,
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000189 "R'''": Single3, 'R"""': Double3,
190 "U'''": Single3, 'U"""': Double3,
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000191 'r': None, 'R': None, 'b': None, 'B': None,
192 'u': None, 'U': None}
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000193
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000194triple_quoted = {}
195for t in ("'''", '"""',
196 "r'''", 'r"""', "R'''", 'R"""',
Guido van Rossum4fe72f92007-11-12 17:40:10 +0000197 "b'''", 'b"""', "B'''", 'B"""',
198 "br'''", 'br"""', "Br'''", 'Br"""',
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000199 "bR'''", 'bR"""', "BR'''", 'BR"""',
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000200 "rb'''", 'rb"""', "rB'''", 'rB"""',
201 "Rb'''", 'Rb"""', "RB'''", 'RB"""',
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000202 "u'''", 'u"""', "U'''", 'U"""',
Christian Heimes0b3847d2012-06-20 11:17:58 +0200203 ):
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000204 triple_quoted[t] = t
205single_quoted = {}
206for t in ("'", '"',
207 "r'", 'r"', "R'", 'R"',
Guido van Rossum4fe72f92007-11-12 17:40:10 +0000208 "b'", 'b"', "B'", 'B"',
209 "br'", 'br"', "Br'", 'Br"',
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000210 "bR'", 'bR"', "BR'", 'BR"' ,
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000211 "rb'", 'rb"', "rB'", 'rB"',
212 "Rb'", 'Rb"', "RB'", 'RB"' ,
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000213 "u'", 'u"', "U'", 'U"',
Christian Heimes0b3847d2012-06-20 11:17:58 +0200214 ):
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000215 single_quoted[t] = t
216
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000217tabsize = 8
Fred Drake9b8d8012000-08-17 04:45:13 +0000218
Ka-Ping Yee28c62bb2001-03-23 05:22:49 +0000219class TokenError(Exception): pass
220
221class StopTokenizing(Exception): pass
Fred Drake9b8d8012000-08-17 04:45:13 +0000222
Tim Peters5ca576e2001-06-18 22:08:13 +0000223
Thomas Wouters89f507f2006-12-13 04:49:30 +0000224class Untokenizer:
225
226 def __init__(self):
227 self.tokens = []
228 self.prev_row = 1
229 self.prev_col = 0
Trent Nelson428de652008-03-18 22:41:35 +0000230 self.encoding = None
Thomas Wouters89f507f2006-12-13 04:49:30 +0000231
232 def add_whitespace(self, start):
233 row, col = start
Terry Jan Reedy5e6db312014-02-17 16:45:48 -0500234 if row < self.prev_row or row == self.prev_row and col < self.prev_col:
235 raise ValueError("start ({},{}) precedes previous end ({},{})"
236 .format(row, col, self.prev_row, self.prev_col))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000237 col_offset = col - self.prev_col
238 if col_offset:
239 self.tokens.append(" " * col_offset)
240
241 def untokenize(self, iterable):
Terry Jan Reedy5b8d2c32014-02-17 23:12:16 -0500242 it = iter(iterable)
243 for t in it:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000244 if len(t) == 2:
Terry Jan Reedy5b8d2c32014-02-17 23:12:16 -0500245 self.compat(t, it)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000246 break
247 tok_type, token, start, end, line = t
Trent Nelson428de652008-03-18 22:41:35 +0000248 if tok_type == ENCODING:
249 self.encoding = token
250 continue
Thomas Wouters89f507f2006-12-13 04:49:30 +0000251 self.add_whitespace(start)
252 self.tokens.append(token)
253 self.prev_row, self.prev_col = end
254 if tok_type in (NEWLINE, NL):
255 self.prev_row += 1
256 self.prev_col = 0
257 return "".join(self.tokens)
258
259 def compat(self, token, iterable):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000260 indents = []
261 toks_append = self.tokens.append
Terry Jan Reedy5b8d2c32014-02-17 23:12:16 -0500262 startline = token[0] in (NEWLINE, NL)
Christian Heimesba4af492008-03-28 00:55:15 +0000263 prevstring = False
Terry Jan Reedy5b8d2c32014-02-17 23:12:16 -0500264
265 for tok in chain([token], iterable):
Thomas Wouters89f507f2006-12-13 04:49:30 +0000266 toknum, tokval = tok[:2]
Trent Nelson428de652008-03-18 22:41:35 +0000267 if toknum == ENCODING:
268 self.encoding = tokval
269 continue
Thomas Wouters89f507f2006-12-13 04:49:30 +0000270
271 if toknum in (NAME, NUMBER):
272 tokval += ' '
273
Christian Heimesba4af492008-03-28 00:55:15 +0000274 # Insert a space between two consecutive strings
275 if toknum == STRING:
276 if prevstring:
277 tokval = ' ' + tokval
278 prevstring = True
279 else:
280 prevstring = False
281
Thomas Wouters89f507f2006-12-13 04:49:30 +0000282 if toknum == INDENT:
283 indents.append(tokval)
284 continue
285 elif toknum == DEDENT:
286 indents.pop()
287 continue
288 elif toknum in (NEWLINE, NL):
289 startline = True
290 elif startline and indents:
291 toks_append(indents[-1])
292 startline = False
293 toks_append(tokval)
Raymond Hettinger68c04532005-06-10 11:05:19 +0000294
Trent Nelson428de652008-03-18 22:41:35 +0000295
Raymond Hettinger68c04532005-06-10 11:05:19 +0000296def untokenize(iterable):
297 """Transform tokens back into Python source code.
Trent Nelson428de652008-03-18 22:41:35 +0000298 It returns a bytes object, encoded using the ENCODING
299 token, which is the first token sequence output by tokenize.
Raymond Hettinger68c04532005-06-10 11:05:19 +0000300
301 Each element returned by the iterable must be a token sequence
Thomas Wouters89f507f2006-12-13 04:49:30 +0000302 with at least two elements, a token number and token value. If
303 only two tokens are passed, the resulting output is poor.
Raymond Hettinger68c04532005-06-10 11:05:19 +0000304
Thomas Wouters89f507f2006-12-13 04:49:30 +0000305 Round-trip invariant for full input:
306 Untokenized source will match input source exactly
307
308 Round-trip invariant for limited intput:
Trent Nelson428de652008-03-18 22:41:35 +0000309 # Output bytes will tokenize the back to the input
310 t1 = [tok[:2] for tok in tokenize(f.readline)]
Raymond Hettinger68c04532005-06-10 11:05:19 +0000311 newcode = untokenize(t1)
Trent Nelson428de652008-03-18 22:41:35 +0000312 readline = BytesIO(newcode).readline
313 t2 = [tok[:2] for tok in tokenize(readline)]
Raymond Hettinger68c04532005-06-10 11:05:19 +0000314 assert t1 == t2
315 """
Thomas Wouters89f507f2006-12-13 04:49:30 +0000316 ut = Untokenizer()
Trent Nelson428de652008-03-18 22:41:35 +0000317 out = ut.untokenize(iterable)
318 if ut.encoding is not None:
319 out = out.encode(ut.encoding)
320 return out
Raymond Hettinger68c04532005-06-10 11:05:19 +0000321
Trent Nelson428de652008-03-18 22:41:35 +0000322
Benjamin Petersond3afada2009-10-09 21:43:09 +0000323def _get_normal_name(orig_enc):
324 """Imitates get_normal_name in tokenizer.c."""
325 # Only care about the first 12 characters.
326 enc = orig_enc[:12].lower().replace("_", "-")
327 if enc == "utf-8" or enc.startswith("utf-8-"):
328 return "utf-8"
329 if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
330 enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
331 return "iso-8859-1"
332 return orig_enc
333
Trent Nelson428de652008-03-18 22:41:35 +0000334def detect_encoding(readline):
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000335 """
Trent Nelson428de652008-03-18 22:41:35 +0000336 The detect_encoding() function is used to detect the encoding that should
Ezio Melotti4bcc7962013-11-25 05:14:51 +0200337 be used to decode a Python source file. It requires one argument, readline,
Trent Nelson428de652008-03-18 22:41:35 +0000338 in the same way as the tokenize() generator.
339
340 It will call readline a maximum of twice, and return the encoding used
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000341 (as a string) and a list of any lines (left as bytes) it has read in.
Trent Nelson428de652008-03-18 22:41:35 +0000342
343 It detects the encoding from the presence of a utf-8 bom or an encoding
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000344 cookie as specified in pep-0263. If both a bom and a cookie are present,
345 but disagree, a SyntaxError will be raised. If the encoding cookie is an
346 invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
Benjamin Peterson689a5582010-03-18 22:29:52 +0000347 'utf-8-sig' is returned.
Trent Nelson428de652008-03-18 22:41:35 +0000348
349 If no encoding is specified, then the default of 'utf-8' will be returned.
350 """
Brett Cannonc33f3f22012-04-20 13:23:54 -0400351 try:
352 filename = readline.__self__.name
353 except AttributeError:
354 filename = None
Trent Nelson428de652008-03-18 22:41:35 +0000355 bom_found = False
356 encoding = None
Benjamin Peterson689a5582010-03-18 22:29:52 +0000357 default = 'utf-8'
Trent Nelson428de652008-03-18 22:41:35 +0000358 def read_or_stop():
359 try:
360 return readline()
361 except StopIteration:
362 return b''
363
364 def find_cookie(line):
365 try:
Martin v. Löwis63674f42012-04-20 14:36:47 +0200366 # Decode as UTF-8. Either the line is an encoding declaration,
367 # in which case it should be pure ASCII, or it must be UTF-8
368 # per default encoding.
369 line_string = line.decode('utf-8')
Trent Nelson428de652008-03-18 22:41:35 +0000370 except UnicodeDecodeError:
Brett Cannonc33f3f22012-04-20 13:23:54 -0400371 msg = "invalid or missing encoding declaration"
372 if filename is not None:
373 msg = '{} for {!r}'.format(msg, filename)
374 raise SyntaxError(msg)
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000375
Serhiy Storchakadafea852013-09-16 23:51:56 +0300376 match = cookie_re.match(line_string)
377 if not match:
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000378 return None
Serhiy Storchakadafea852013-09-16 23:51:56 +0300379 encoding = _get_normal_name(match.group(1))
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000380 try:
381 codec = lookup(encoding)
382 except LookupError:
383 # This behaviour mimics the Python interpreter
Brett Cannonc33f3f22012-04-20 13:23:54 -0400384 if filename is None:
385 msg = "unknown encoding: " + encoding
386 else:
387 msg = "unknown encoding for {!r}: {}".format(filename,
388 encoding)
389 raise SyntaxError(msg)
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000390
Benjamin Peterson1613ed82010-03-18 22:34:15 +0000391 if bom_found:
Florent Xicluna11f0b412012-07-07 12:13:35 +0200392 if encoding != 'utf-8':
Benjamin Peterson1613ed82010-03-18 22:34:15 +0000393 # This behaviour mimics the Python interpreter
Brett Cannonc33f3f22012-04-20 13:23:54 -0400394 if filename is None:
395 msg = 'encoding problem: utf-8'
396 else:
397 msg = 'encoding problem for {!r}: utf-8'.format(filename)
398 raise SyntaxError(msg)
Benjamin Peterson1613ed82010-03-18 22:34:15 +0000399 encoding += '-sig'
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000400 return encoding
Trent Nelson428de652008-03-18 22:41:35 +0000401
402 first = read_or_stop()
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000403 if first.startswith(BOM_UTF8):
Trent Nelson428de652008-03-18 22:41:35 +0000404 bom_found = True
405 first = first[3:]
Benjamin Peterson689a5582010-03-18 22:29:52 +0000406 default = 'utf-8-sig'
Trent Nelson428de652008-03-18 22:41:35 +0000407 if not first:
Benjamin Peterson689a5582010-03-18 22:29:52 +0000408 return default, []
Trent Nelson428de652008-03-18 22:41:35 +0000409
410 encoding = find_cookie(first)
411 if encoding:
412 return encoding, [first]
Serhiy Storchaka768c16c2014-01-09 18:36:09 +0200413 if not blank_re.match(first):
414 return default, [first]
Trent Nelson428de652008-03-18 22:41:35 +0000415
416 second = read_or_stop()
417 if not second:
Benjamin Peterson689a5582010-03-18 22:29:52 +0000418 return default, [first]
Trent Nelson428de652008-03-18 22:41:35 +0000419
420 encoding = find_cookie(second)
421 if encoding:
422 return encoding, [first, second]
423
Benjamin Peterson689a5582010-03-18 22:29:52 +0000424 return default, [first, second]
Trent Nelson428de652008-03-18 22:41:35 +0000425
426
Victor Stinner58c07522010-11-09 01:08:59 +0000427def open(filename):
428 """Open a file in read only mode using the encoding detected by
429 detect_encoding().
430 """
Brett Cannonf3042782011-02-22 03:25:12 +0000431 buffer = builtins.open(filename, 'rb')
Victor Stinner58c07522010-11-09 01:08:59 +0000432 encoding, lines = detect_encoding(buffer.readline)
433 buffer.seek(0)
434 text = TextIOWrapper(buffer, encoding, line_buffering=True)
435 text.mode = 'r'
436 return text
437
438
Trent Nelson428de652008-03-18 22:41:35 +0000439def tokenize(readline):
440 """
441 The tokenize() generator requires one argment, readline, which
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000442 must be a callable object which provides the same interface as the
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000443 readline() method of built-in file objects. Each call to the function
Trent Nelson428de652008-03-18 22:41:35 +0000444 should return one line of input as bytes. Alternately, readline
Raymond Hettinger68c04532005-06-10 11:05:19 +0000445 can be a callable function terminating with StopIteration:
Trent Nelson428de652008-03-18 22:41:35 +0000446 readline = open(myfile, 'rb').__next__ # Example of alternate readline
Tim Peters8ac14952002-05-23 15:15:30 +0000447
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000448 The generator produces 5-tuples with these members: the token type; the
449 token string; a 2-tuple (srow, scol) of ints specifying the row and
450 column where the token begins in the source; a 2-tuple (erow, ecol) of
451 ints specifying the row and column where the token ends in the source;
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000452 and the line on which the token was found. The line passed is the
Tim Peters8ac14952002-05-23 15:15:30 +0000453 logical line; continuation lines are included.
Trent Nelson428de652008-03-18 22:41:35 +0000454
455 The first token sequence will always be an ENCODING token
456 which tells you which encoding was used to decode the bytes stream.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000457 """
Benjamin Peterson21db77e2009-11-14 16:27:26 +0000458 # This import is here to avoid problems when the itertools module is not
459 # built yet and tokenize is imported.
Benjamin Peterson81dd8b92009-11-14 18:09:17 +0000460 from itertools import chain, repeat
Trent Nelson428de652008-03-18 22:41:35 +0000461 encoding, consumed = detect_encoding(readline)
Benjamin Peterson81dd8b92009-11-14 18:09:17 +0000462 rl_gen = iter(readline, b"")
463 empty = repeat(b"")
464 return _tokenize(chain(consumed, rl_gen, empty).__next__, encoding)
Trent Nelson428de652008-03-18 22:41:35 +0000465
466
467def _tokenize(readline, encoding):
Guido van Rossum1aec3231997-04-08 14:24:39 +0000468 lnum = parenlev = continued = 0
Benjamin Peterson33856de2010-08-30 14:41:20 +0000469 numchars = '0123456789'
Guido van Rossumde655271997-04-09 17:15:54 +0000470 contstr, needcont = '', 0
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000471 contline = None
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000472 indents = [0]
Guido van Rossum1aec3231997-04-08 14:24:39 +0000473
Trent Nelson428de652008-03-18 22:41:35 +0000474 if encoding is not None:
Benjamin Peterson689a5582010-03-18 22:29:52 +0000475 if encoding == "utf-8-sig":
476 # BOM will already have been stripped.
477 encoding = "utf-8"
Raymond Hettingera48db392009-04-29 00:34:27 +0000478 yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '')
Benjamin Peterson0fe14382008-06-05 23:07:42 +0000479 while True: # loop over lines in stream
Raymond Hettinger68c04532005-06-10 11:05:19 +0000480 try:
481 line = readline()
482 except StopIteration:
Trent Nelson428de652008-03-18 22:41:35 +0000483 line = b''
484
485 if encoding is not None:
486 line = line.decode(encoding)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000487 lnum += 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000488 pos, max = 0, len(line)
489
490 if contstr: # continued string
Guido van Rossumde655271997-04-09 17:15:54 +0000491 if not line:
Collin Winterce36ad82007-08-30 01:19:48 +0000492 raise TokenError("EOF in multi-line string", strstart)
Guido van Rossum3b631771997-10-27 20:44:15 +0000493 endmatch = endprog.match(line)
494 if endmatch:
495 pos = end = endmatch.end(0)
Raymond Hettingera48db392009-04-29 00:34:27 +0000496 yield TokenInfo(STRING, contstr + line[:end],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000497 strstart, (lnum, end), contline + line)
Guido van Rossumde655271997-04-09 17:15:54 +0000498 contstr, needcont = '', 0
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000499 contline = None
Guido van Rossumde655271997-04-09 17:15:54 +0000500 elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
Raymond Hettingera48db392009-04-29 00:34:27 +0000501 yield TokenInfo(ERRORTOKEN, contstr + line,
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000502 strstart, (lnum, len(line)), contline)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000503 contstr = ''
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000504 contline = None
Guido van Rossumde655271997-04-09 17:15:54 +0000505 continue
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000506 else:
507 contstr = contstr + line
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000508 contline = contline + line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000509 continue
510
Guido van Rossum1aec3231997-04-08 14:24:39 +0000511 elif parenlev == 0 and not continued: # new statement
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000512 if not line: break
513 column = 0
Guido van Rossum1aec3231997-04-08 14:24:39 +0000514 while pos < max: # measure leading whitespace
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000515 if line[pos] == ' ':
516 column += 1
517 elif line[pos] == '\t':
518 column = (column//tabsize + 1)*tabsize
519 elif line[pos] == '\f':
520 column = 0
521 else:
522 break
523 pos += 1
524 if pos == max:
525 break
Guido van Rossum1aec3231997-04-08 14:24:39 +0000526
527 if line[pos] in '#\r\n': # skip comments or blank lines
Thomas Wouters89f507f2006-12-13 04:49:30 +0000528 if line[pos] == '#':
529 comment_token = line[pos:].rstrip('\r\n')
530 nl_pos = pos + len(comment_token)
Raymond Hettingera48db392009-04-29 00:34:27 +0000531 yield TokenInfo(COMMENT, comment_token,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000532 (lnum, pos), (lnum, pos + len(comment_token)), line)
Raymond Hettingera48db392009-04-29 00:34:27 +0000533 yield TokenInfo(NL, line[nl_pos:],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000534 (lnum, nl_pos), (lnum, len(line)), line)
535 else:
Raymond Hettingera48db392009-04-29 00:34:27 +0000536 yield TokenInfo((NL, COMMENT)[line[pos] == '#'], line[pos:],
Guido van Rossum1aec3231997-04-08 14:24:39 +0000537 (lnum, pos), (lnum, len(line)), line)
538 continue
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000539
540 if column > indents[-1]: # count indents or dedents
541 indents.append(column)
Raymond Hettingera48db392009-04-29 00:34:27 +0000542 yield TokenInfo(INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000543 while column < indents[-1]:
Raymond Hettingerda99d1c2005-06-21 07:43:58 +0000544 if column not in indents:
545 raise IndentationError(
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000546 "unindent does not match any outer indentation level",
547 ("<tokenize>", lnum, pos, line))
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000548 indents = indents[:-1]
Raymond Hettingera48db392009-04-29 00:34:27 +0000549 yield TokenInfo(DEDENT, '', (lnum, pos), (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000550
551 else: # continued statement
Guido van Rossumde655271997-04-09 17:15:54 +0000552 if not line:
Collin Winterce36ad82007-08-30 01:19:48 +0000553 raise TokenError("EOF in multi-line statement", (lnum, 0))
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000554 continued = 0
555
556 while pos < max:
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200557 pseudomatch = _compile(PseudoToken).match(line, pos)
Guido van Rossum3b631771997-10-27 20:44:15 +0000558 if pseudomatch: # scan for tokens
559 start, end = pseudomatch.span(1)
Guido van Rossumde655271997-04-09 17:15:54 +0000560 spos, epos, pos = (lnum, start), (lnum, end), end
Ezio Melotti2cc3b4b2012-11-03 17:38:43 +0200561 if start == end:
562 continue
Guido van Rossum1aec3231997-04-08 14:24:39 +0000563 token, initial = line[start:end], line[start]
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000564
Georg Brandldde00282007-03-18 19:01:53 +0000565 if (initial in numchars or # ordinary number
566 (initial == '.' and token != '.' and token != '...')):
Raymond Hettingera48db392009-04-29 00:34:27 +0000567 yield TokenInfo(NUMBER, token, spos, epos, line)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000568 elif initial in '\r\n':
Raymond Hettingera48db392009-04-29 00:34:27 +0000569 yield TokenInfo(NL if parenlev > 0 else NEWLINE,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000570 token, spos, epos, line)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000571 elif initial == '#':
Thomas Wouters89f507f2006-12-13 04:49:30 +0000572 assert not token.endswith("\n")
Raymond Hettingera48db392009-04-29 00:34:27 +0000573 yield TokenInfo(COMMENT, token, spos, epos, line)
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000574 elif token in triple_quoted:
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200575 endprog = _compile(endpats[token])
Guido van Rossum3b631771997-10-27 20:44:15 +0000576 endmatch = endprog.match(line, pos)
577 if endmatch: # all on one line
578 pos = endmatch.end(0)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000579 token = line[start:pos]
Raymond Hettingera48db392009-04-29 00:34:27 +0000580 yield TokenInfo(STRING, token, spos, (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000581 else:
Guido van Rossum1aec3231997-04-08 14:24:39 +0000582 strstart = (lnum, start) # multiple lines
583 contstr = line[start:]
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000584 contline = line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000585 break
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000586 elif initial in single_quoted or \
587 token[:2] in single_quoted or \
588 token[:3] in single_quoted:
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000589 if token[-1] == '\n': # continued string
Guido van Rossum1aec3231997-04-08 14:24:39 +0000590 strstart = (lnum, start)
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200591 endprog = _compile(endpats[initial] or
592 endpats[token[1]] or
593 endpats[token[2]])
Guido van Rossumde655271997-04-09 17:15:54 +0000594 contstr, needcont = line[start:], 1
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000595 contline = line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000596 break
597 else: # ordinary string
Raymond Hettingera48db392009-04-29 00:34:27 +0000598 yield TokenInfo(STRING, token, spos, epos, line)
Benjamin Peterson33856de2010-08-30 14:41:20 +0000599 elif initial.isidentifier(): # ordinary name
Raymond Hettingera48db392009-04-29 00:34:27 +0000600 yield TokenInfo(NAME, token, spos, epos, line)
Guido van Rossum3b631771997-10-27 20:44:15 +0000601 elif initial == '\\': # continued stmt
602 continued = 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000603 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000604 if initial in '([{':
605 parenlev += 1
606 elif initial in ')]}':
607 parenlev -= 1
Raymond Hettingera48db392009-04-29 00:34:27 +0000608 yield TokenInfo(OP, token, spos, epos, line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000609 else:
Raymond Hettingera48db392009-04-29 00:34:27 +0000610 yield TokenInfo(ERRORTOKEN, line[pos],
Guido van Rossumde655271997-04-09 17:15:54 +0000611 (lnum, pos), (lnum, pos+1), line)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000612 pos += 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000613
614 for indent in indents[1:]: # pop remaining indent levels
Raymond Hettingera48db392009-04-29 00:34:27 +0000615 yield TokenInfo(DEDENT, '', (lnum, 0), (lnum, 0), '')
616 yield TokenInfo(ENDMARKER, '', (lnum, 0), (lnum, 0), '')
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000617
Trent Nelson428de652008-03-18 22:41:35 +0000618
619# An undocumented, backwards compatible, API for all the places in the standard
620# library that expect to be able to use tokenize with strings
621def generate_tokens(readline):
622 return _tokenize(readline, None)
Raymond Hettinger6c60d092010-09-09 04:32:39 +0000623
Meador Inge14c0f032011-10-07 08:53:38 -0500624def main():
625 import argparse
626
627 # Helper error handling routines
628 def perror(message):
629 print(message, file=sys.stderr)
630
631 def error(message, filename=None, location=None):
632 if location:
633 args = (filename,) + location + (message,)
634 perror("%s:%d:%d: error: %s" % args)
635 elif filename:
636 perror("%s: error: %s" % (filename, message))
637 else:
638 perror("error: %s" % message)
639 sys.exit(1)
640
641 # Parse the arguments and options
642 parser = argparse.ArgumentParser(prog='python -m tokenize')
643 parser.add_argument(dest='filename', nargs='?',
644 metavar='filename.py',
645 help='the file to tokenize; defaults to stdin')
Meador Inge00c7f852012-01-19 00:44:45 -0600646 parser.add_argument('-e', '--exact', dest='exact', action='store_true',
647 help='display token names using the exact type')
Meador Inge14c0f032011-10-07 08:53:38 -0500648 args = parser.parse_args()
649
650 try:
651 # Tokenize the input
652 if args.filename:
653 filename = args.filename
654 with builtins.open(filename, 'rb') as f:
655 tokens = list(tokenize(f.readline))
656 else:
657 filename = "<stdin>"
658 tokens = _tokenize(sys.stdin.readline, None)
659
660 # Output the tokenization
661 for token in tokens:
Meador Inge00c7f852012-01-19 00:44:45 -0600662 token_type = token.type
663 if args.exact:
664 token_type = token.exact_type
Meador Inge14c0f032011-10-07 08:53:38 -0500665 token_range = "%d,%d-%d,%d:" % (token.start + token.end)
666 print("%-20s%-15s%-15r" %
Meador Inge00c7f852012-01-19 00:44:45 -0600667 (token_range, tok_name[token_type], token.string))
Meador Inge14c0f032011-10-07 08:53:38 -0500668 except IndentationError as err:
669 line, column = err.args[1][1:3]
670 error(err.args[0], filename, (line, column))
671 except TokenError as err:
672 line, column = err.args[1]
673 error(err.args[0], filename, (line, column))
674 except SyntaxError as err:
675 error(err, filename)
676 except IOError as err:
677 error(err)
678 except KeyboardInterrupt:
679 print("interrupted\n")
680 except Exception as err:
681 perror("unexpected error: %s" % err)
682 raise
683
Raymond Hettinger6c60d092010-09-09 04:32:39 +0000684if __name__ == "__main__":
Meador Inge14c0f032011-10-07 08:53:38 -0500685 main()