blob: c156450d047fa005647955ff8c9a5755271b7d50 [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
Florent Xicluna43e4ea12010-09-03 19:54:02 +000028import re
29import sys
Guido van Rossumfc6f5331997-03-07 00:21:12 +000030from token import *
Benjamin Peterson433f32c2008-12-12 01:25:05 +000031from codecs import lookup, BOM_UTF8
Raymond Hettinger3fb79c72010-09-09 07:15:18 +000032import collections
Victor Stinner58c07522010-11-09 01:08:59 +000033from io import TextIOWrapper
Serhiy Storchakadafea852013-09-16 23:51:56 +030034cookie_re = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)', re.ASCII)
Serhiy Storchaka768c16c2014-01-09 18:36:09 +020035blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII)
Guido van Rossum4d8e8591992-01-01 19:34:47 +000036
Skip Montanaro40fc1602001-03-01 04:27:19 +000037import token
Alexander Belopolskyb9d10d02010-11-11 14:07:41 +000038__all__ = token.__all__ + ["COMMENT", "tokenize", "detect_encoding",
39 "NL", "untokenize", "ENCODING", "TokenInfo"]
Skip Montanaro40fc1602001-03-01 04:27:19 +000040del token
41
Guido van Rossum1aec3231997-04-08 14:24:39 +000042COMMENT = N_TOKENS
43tok_name[COMMENT] = 'COMMENT'
Guido van Rossuma90c78b1998-04-03 16:05:38 +000044NL = N_TOKENS + 1
45tok_name[NL] = 'NL'
Trent Nelson428de652008-03-18 22:41:35 +000046ENCODING = N_TOKENS + 2
47tok_name[ENCODING] = 'ENCODING'
48N_TOKENS += 3
Meador Inge00c7f852012-01-19 00:44:45 -060049EXACT_TOKEN_TYPES = {
50 '(': LPAR,
51 ')': RPAR,
52 '[': LSQB,
53 ']': RSQB,
54 ':': COLON,
55 ',': COMMA,
56 ';': SEMI,
57 '+': PLUS,
58 '-': MINUS,
59 '*': STAR,
60 '/': SLASH,
61 '|': VBAR,
62 '&': AMPER,
63 '<': LESS,
64 '>': GREATER,
65 '=': EQUAL,
66 '.': DOT,
67 '%': PERCENT,
68 '{': LBRACE,
69 '}': RBRACE,
70 '==': EQEQUAL,
71 '!=': NOTEQUAL,
72 '<=': LESSEQUAL,
73 '>=': GREATEREQUAL,
74 '~': TILDE,
75 '^': CIRCUMFLEX,
76 '<<': LEFTSHIFT,
77 '>>': RIGHTSHIFT,
78 '**': DOUBLESTAR,
79 '+=': PLUSEQUAL,
80 '-=': MINEQUAL,
81 '*=': STAREQUAL,
82 '/=': SLASHEQUAL,
83 '%=': PERCENTEQUAL,
84 '&=': AMPEREQUAL,
85 '|=': VBAREQUAL,
86 '^=': CIRCUMFLEXEQUAL,
87 '<<=': LEFTSHIFTEQUAL,
88 '>>=': RIGHTSHIFTEQUAL,
89 '**=': DOUBLESTAREQUAL,
90 '//': DOUBLESLASH,
91 '//=': DOUBLESLASHEQUAL,
92 '@': AT
93}
Guido van Rossum1aec3231997-04-08 14:24:39 +000094
Raymond Hettinger3fb79c72010-09-09 07:15:18 +000095class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
Raymond Hettingeraa17a7f2009-04-29 14:21:25 +000096 def __repr__(self):
Raymond Hettingera0e79402010-09-09 08:29:05 +000097 annotated_type = '%d (%s)' % (self.type, tok_name[self.type])
98 return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' %
99 self._replace(type=annotated_type))
Raymond Hettingeraa17a7f2009-04-29 14:21:25 +0000100
Meador Inge00c7f852012-01-19 00:44:45 -0600101 @property
102 def exact_type(self):
103 if self.type == OP and self.string in EXACT_TOKEN_TYPES:
104 return EXACT_TOKEN_TYPES[self.string]
105 else:
106 return self.type
107
Eric S. Raymondb08b2d32001-02-09 11:10:16 +0000108def group(*choices): return '(' + '|'.join(choices) + ')'
Guido van Rossum68468eb2003-02-27 20:14:51 +0000109def any(*choices): return group(*choices) + '*'
110def maybe(*choices): return group(*choices) + '?'
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000111
Antoine Pitroufd036452008-08-19 17:56:33 +0000112# Note: we use unicode matching for names ("\w") but ascii matching for
113# number literals.
Guido van Rossum3b631771997-10-27 20:44:15 +0000114Whitespace = r'[ \f\t]*'
115Comment = r'#[^\r\n]*'
116Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
Benjamin Peterson33856de2010-08-30 14:41:20 +0000117Name = r'\w+'
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000118
Antoine Pitroufd036452008-08-19 17:56:33 +0000119Hexnumber = r'0[xX][0-9a-fA-F]+'
Georg Brandlfceab5a2008-01-19 20:08:23 +0000120Binnumber = r'0[bB][01]+'
121Octnumber = r'0[oO][0-7]+'
Antoine Pitroufd036452008-08-19 17:56:33 +0000122Decnumber = r'(?:0+|[1-9][0-9]*)'
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000123Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
Antoine Pitroufd036452008-08-19 17:56:33 +0000124Exponent = r'[eE][-+]?[0-9]+'
125Pointfloat = group(r'[0-9]+\.[0-9]*', r'\.[0-9]+') + maybe(Exponent)
126Expfloat = r'[0-9]+' + Exponent
Guido van Rossum1aec3231997-04-08 14:24:39 +0000127Floatnumber = group(Pointfloat, Expfloat)
Antoine Pitroufd036452008-08-19 17:56:33 +0000128Imagnumber = group(r'[0-9]+[jJ]', Floatnumber + r'[jJ]')
Guido van Rossum1aec3231997-04-08 14:24:39 +0000129Number = group(Imagnumber, Floatnumber, Intnumber)
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000130
Christian Heimes0b3847d2012-06-20 11:17:58 +0200131StringPrefix = r'(?:[bB][rR]?|[rR][bB]?|[uU])?'
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000132
Tim Petersde495832000-10-07 05:09:39 +0000133# Tail end of ' string.
134Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
135# Tail end of " string.
136Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
137# Tail end of ''' string.
138Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
139# Tail end of """ string.
140Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000141Triple = group(StringPrefix + "'''", StringPrefix + '"""')
Tim Petersde495832000-10-07 05:09:39 +0000142# Single-line ' or " string.
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000143String = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
144 StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000145
Tim Petersde495832000-10-07 05:09:39 +0000146# Because of leftmost-then-longest match semantics, be sure to put the
147# longest operators first (e.g., if = came before ==, == would get
148# recognized as two instances of =).
Guido van Rossumb053cd82006-08-24 03:53:23 +0000149Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=",
Neal Norwitzc1505362006-12-28 06:47:50 +0000150 r"//=?", r"->",
Tim Petersde495832000-10-07 05:09:39 +0000151 r"[+\-*/%&|^=<>]=?",
152 r"~")
Thomas Wouterse1519a12000-08-24 21:44:52 +0000153
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000154Bracket = '[][(){}]'
Georg Brandldde00282007-03-18 19:01:53 +0000155Special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]')
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000156Funny = group(Operator, Bracket, Special)
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000157
Guido van Rossum3b631771997-10-27 20:44:15 +0000158PlainToken = group(Number, Funny, String, Name)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000159Token = Ignore + PlainToken
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000160
Tim Petersde495832000-10-07 05:09:39 +0000161# First (or only) line of ' or " string.
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000162ContStr = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
Ka-Ping Yee1ff08b12001-01-15 22:04:30 +0000163 group("'", r'\\\r?\n'),
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000164 StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
Ka-Ping Yee1ff08b12001-01-15 22:04:30 +0000165 group('"', r'\\\r?\n'))
Ezio Melotti2cc3b4b2012-11-03 17:38:43 +0200166PseudoExtras = group(r'\\\r?\n|\Z', Comment, Triple)
Guido van Rossum3b631771997-10-27 20:44:15 +0000167PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000168
Benjamin Peterson33856de2010-08-30 14:41:20 +0000169def _compile(expr):
170 return re.compile(expr, re.UNICODE)
171
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200172endpats = {"'": Single, '"': Double,
173 "'''": Single3, '"""': Double3,
174 "r'''": Single3, 'r"""': Double3,
175 "b'''": Single3, 'b"""': Double3,
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200176 "R'''": Single3, 'R"""': Double3,
177 "B'''": Single3, 'B"""': Double3,
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000178 "br'''": Single3, 'br"""': Double3,
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200179 "bR'''": Single3, 'bR"""': Double3,
180 "Br'''": Single3, 'Br"""': Double3,
181 "BR'''": Single3, 'BR"""': Double3,
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000182 "rb'''": Single3, 'rb"""': Double3,
183 "Rb'''": Single3, 'Rb"""': Double3,
184 "rB'''": Single3, 'rB"""': Double3,
185 "RB'''": Single3, 'RB"""': Double3,
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000186 "u'''": Single3, 'u"""': Double3,
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000187 "R'''": Single3, 'R"""': Double3,
188 "U'''": Single3, 'U"""': Double3,
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000189 'r': None, 'R': None, 'b': None, 'B': None,
190 'u': None, 'U': None}
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000191
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000192triple_quoted = {}
193for t in ("'''", '"""',
194 "r'''", 'r"""', "R'''", 'R"""',
Guido van Rossum4fe72f92007-11-12 17:40:10 +0000195 "b'''", 'b"""', "B'''", 'B"""',
196 "br'''", 'br"""', "Br'''", 'Br"""',
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000197 "bR'''", 'bR"""', "BR'''", 'BR"""',
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000198 "rb'''", 'rb"""', "rB'''", 'rB"""',
199 "Rb'''", 'Rb"""', "RB'''", 'RB"""',
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000200 "u'''", 'u"""', "U'''", 'U"""',
Christian Heimes0b3847d2012-06-20 11:17:58 +0200201 ):
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000202 triple_quoted[t] = t
203single_quoted = {}
204for t in ("'", '"',
205 "r'", 'r"', "R'", 'R"',
Guido van Rossum4fe72f92007-11-12 17:40:10 +0000206 "b'", 'b"', "B'", 'B"',
207 "br'", 'br"', "Br'", 'Br"',
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000208 "bR'", 'bR"', "BR'", 'BR"' ,
Armin Ronacherc0eaeca2012-03-04 13:07:57 +0000209 "rb'", 'rb"', "rB'", 'rB"',
210 "Rb'", 'Rb"', "RB'", 'RB"' ,
Armin Ronacher6ecf77b2012-03-04 12:04:06 +0000211 "u'", 'u"', "U'", 'U"',
Christian Heimes0b3847d2012-06-20 11:17:58 +0200212 ):
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000213 single_quoted[t] = t
214
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000215tabsize = 8
Fred Drake9b8d8012000-08-17 04:45:13 +0000216
Ka-Ping Yee28c62bb2001-03-23 05:22:49 +0000217class TokenError(Exception): pass
218
219class StopTokenizing(Exception): pass
Fred Drake9b8d8012000-08-17 04:45:13 +0000220
Tim Peters5ca576e2001-06-18 22:08:13 +0000221
Thomas Wouters89f507f2006-12-13 04:49:30 +0000222class Untokenizer:
223
224 def __init__(self):
225 self.tokens = []
226 self.prev_row = 1
227 self.prev_col = 0
Trent Nelson428de652008-03-18 22:41:35 +0000228 self.encoding = None
Thomas Wouters89f507f2006-12-13 04:49:30 +0000229
230 def add_whitespace(self, start):
231 row, col = start
Terry Jan Reedy5e6db312014-02-17 16:45:48 -0500232 if row < self.prev_row or row == self.prev_row and col < self.prev_col:
233 raise ValueError("start ({},{}) precedes previous end ({},{})"
234 .format(row, col, self.prev_row, self.prev_col))
Thomas Wouters89f507f2006-12-13 04:49:30 +0000235 col_offset = col - self.prev_col
236 if col_offset:
237 self.tokens.append(" " * col_offset)
238
239 def untokenize(self, iterable):
240 for t in iterable:
241 if len(t) == 2:
242 self.compat(t, iterable)
243 break
244 tok_type, token, start, end, line = t
Trent Nelson428de652008-03-18 22:41:35 +0000245 if tok_type == ENCODING:
246 self.encoding = token
247 continue
Thomas Wouters89f507f2006-12-13 04:49:30 +0000248 self.add_whitespace(start)
249 self.tokens.append(token)
250 self.prev_row, self.prev_col = end
251 if tok_type in (NEWLINE, NL):
252 self.prev_row += 1
253 self.prev_col = 0
254 return "".join(self.tokens)
255
256 def compat(self, token, iterable):
257 startline = False
258 indents = []
259 toks_append = self.tokens.append
260 toknum, tokval = token
Trent Nelson428de652008-03-18 22:41:35 +0000261
Thomas Wouters89f507f2006-12-13 04:49:30 +0000262 if toknum in (NAME, NUMBER):
263 tokval += ' '
264 if toknum in (NEWLINE, NL):
265 startline = True
Christian Heimesba4af492008-03-28 00:55:15 +0000266 prevstring = False
Thomas Wouters89f507f2006-12-13 04:49:30 +0000267 for tok in iterable:
268 toknum, tokval = tok[:2]
Trent Nelson428de652008-03-18 22:41:35 +0000269 if toknum == ENCODING:
270 self.encoding = tokval
271 continue
Thomas Wouters89f507f2006-12-13 04:49:30 +0000272
273 if toknum in (NAME, NUMBER):
274 tokval += ' '
275
Christian Heimesba4af492008-03-28 00:55:15 +0000276 # Insert a space between two consecutive strings
277 if toknum == STRING:
278 if prevstring:
279 tokval = ' ' + tokval
280 prevstring = True
281 else:
282 prevstring = False
283
Thomas Wouters89f507f2006-12-13 04:49:30 +0000284 if toknum == INDENT:
285 indents.append(tokval)
286 continue
287 elif toknum == DEDENT:
288 indents.pop()
289 continue
290 elif toknum in (NEWLINE, NL):
291 startline = True
292 elif startline and indents:
293 toks_append(indents[-1])
294 startline = False
295 toks_append(tokval)
Raymond Hettinger68c04532005-06-10 11:05:19 +0000296
Trent Nelson428de652008-03-18 22:41:35 +0000297
Raymond Hettinger68c04532005-06-10 11:05:19 +0000298def untokenize(iterable):
299 """Transform tokens back into Python source code.
Trent Nelson428de652008-03-18 22:41:35 +0000300 It returns a bytes object, encoded using the ENCODING
301 token, which is the first token sequence output by tokenize.
Raymond Hettinger68c04532005-06-10 11:05:19 +0000302
303 Each element returned by the iterable must be a token sequence
Thomas Wouters89f507f2006-12-13 04:49:30 +0000304 with at least two elements, a token number and token value. If
305 only two tokens are passed, the resulting output is poor.
Raymond Hettinger68c04532005-06-10 11:05:19 +0000306
Thomas Wouters89f507f2006-12-13 04:49:30 +0000307 Round-trip invariant for full input:
308 Untokenized source will match input source exactly
309
310 Round-trip invariant for limited intput:
Trent Nelson428de652008-03-18 22:41:35 +0000311 # Output bytes will tokenize the back to the input
312 t1 = [tok[:2] for tok in tokenize(f.readline)]
Raymond Hettinger68c04532005-06-10 11:05:19 +0000313 newcode = untokenize(t1)
Trent Nelson428de652008-03-18 22:41:35 +0000314 readline = BytesIO(newcode).readline
315 t2 = [tok[:2] for tok in tokenize(readline)]
Raymond Hettinger68c04532005-06-10 11:05:19 +0000316 assert t1 == t2
317 """
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318 ut = Untokenizer()
Trent Nelson428de652008-03-18 22:41:35 +0000319 out = ut.untokenize(iterable)
320 if ut.encoding is not None:
321 out = out.encode(ut.encoding)
322 return out
Raymond Hettinger68c04532005-06-10 11:05:19 +0000323
Trent Nelson428de652008-03-18 22:41:35 +0000324
Benjamin Petersond3afada2009-10-09 21:43:09 +0000325def _get_normal_name(orig_enc):
326 """Imitates get_normal_name in tokenizer.c."""
327 # Only care about the first 12 characters.
328 enc = orig_enc[:12].lower().replace("_", "-")
329 if enc == "utf-8" or enc.startswith("utf-8-"):
330 return "utf-8"
331 if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
332 enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
333 return "iso-8859-1"
334 return orig_enc
335
Trent Nelson428de652008-03-18 22:41:35 +0000336def detect_encoding(readline):
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000337 """
Trent Nelson428de652008-03-18 22:41:35 +0000338 The detect_encoding() function is used to detect the encoding that should
Ezio Melotti4bcc7962013-11-25 05:14:51 +0200339 be used to decode a Python source file. It requires one argument, readline,
Trent Nelson428de652008-03-18 22:41:35 +0000340 in the same way as the tokenize() generator.
341
342 It will call readline a maximum of twice, and return the encoding used
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000343 (as a string) and a list of any lines (left as bytes) it has read in.
Trent Nelson428de652008-03-18 22:41:35 +0000344
345 It detects the encoding from the presence of a utf-8 bom or an encoding
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000346 cookie as specified in pep-0263. If both a bom and a cookie are present,
347 but disagree, a SyntaxError will be raised. If the encoding cookie is an
348 invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
Benjamin Peterson689a5582010-03-18 22:29:52 +0000349 'utf-8-sig' is returned.
Trent Nelson428de652008-03-18 22:41:35 +0000350
351 If no encoding is specified, then the default of 'utf-8' will be returned.
352 """
Brett Cannonc33f3f22012-04-20 13:23:54 -0400353 try:
354 filename = readline.__self__.name
355 except AttributeError:
356 filename = None
Trent Nelson428de652008-03-18 22:41:35 +0000357 bom_found = False
358 encoding = None
Benjamin Peterson689a5582010-03-18 22:29:52 +0000359 default = 'utf-8'
Trent Nelson428de652008-03-18 22:41:35 +0000360 def read_or_stop():
361 try:
362 return readline()
363 except StopIteration:
364 return b''
365
366 def find_cookie(line):
367 try:
Martin v. Löwis63674f42012-04-20 14:36:47 +0200368 # Decode as UTF-8. Either the line is an encoding declaration,
369 # in which case it should be pure ASCII, or it must be UTF-8
370 # per default encoding.
371 line_string = line.decode('utf-8')
Trent Nelson428de652008-03-18 22:41:35 +0000372 except UnicodeDecodeError:
Brett Cannonc33f3f22012-04-20 13:23:54 -0400373 msg = "invalid or missing encoding declaration"
374 if filename is not None:
375 msg = '{} for {!r}'.format(msg, filename)
376 raise SyntaxError(msg)
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000377
Serhiy Storchakadafea852013-09-16 23:51:56 +0300378 match = cookie_re.match(line_string)
379 if not match:
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000380 return None
Serhiy Storchakadafea852013-09-16 23:51:56 +0300381 encoding = _get_normal_name(match.group(1))
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000382 try:
383 codec = lookup(encoding)
384 except LookupError:
385 # This behaviour mimics the Python interpreter
Brett Cannonc33f3f22012-04-20 13:23:54 -0400386 if filename is None:
387 msg = "unknown encoding: " + encoding
388 else:
389 msg = "unknown encoding for {!r}: {}".format(filename,
390 encoding)
391 raise SyntaxError(msg)
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000392
Benjamin Peterson1613ed82010-03-18 22:34:15 +0000393 if bom_found:
Florent Xicluna11f0b412012-07-07 12:13:35 +0200394 if encoding != 'utf-8':
Benjamin Peterson1613ed82010-03-18 22:34:15 +0000395 # This behaviour mimics the Python interpreter
Brett Cannonc33f3f22012-04-20 13:23:54 -0400396 if filename is None:
397 msg = 'encoding problem: utf-8'
398 else:
399 msg = 'encoding problem for {!r}: utf-8'.format(filename)
400 raise SyntaxError(msg)
Benjamin Peterson1613ed82010-03-18 22:34:15 +0000401 encoding += '-sig'
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000402 return encoding
Trent Nelson428de652008-03-18 22:41:35 +0000403
404 first = read_or_stop()
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000405 if first.startswith(BOM_UTF8):
Trent Nelson428de652008-03-18 22:41:35 +0000406 bom_found = True
407 first = first[3:]
Benjamin Peterson689a5582010-03-18 22:29:52 +0000408 default = 'utf-8-sig'
Trent Nelson428de652008-03-18 22:41:35 +0000409 if not first:
Benjamin Peterson689a5582010-03-18 22:29:52 +0000410 return default, []
Trent Nelson428de652008-03-18 22:41:35 +0000411
412 encoding = find_cookie(first)
413 if encoding:
414 return encoding, [first]
Serhiy Storchaka768c16c2014-01-09 18:36:09 +0200415 if not blank_re.match(first):
416 return default, [first]
Trent Nelson428de652008-03-18 22:41:35 +0000417
418 second = read_or_stop()
419 if not second:
Benjamin Peterson689a5582010-03-18 22:29:52 +0000420 return default, [first]
Trent Nelson428de652008-03-18 22:41:35 +0000421
422 encoding = find_cookie(second)
423 if encoding:
424 return encoding, [first, second]
425
Benjamin Peterson689a5582010-03-18 22:29:52 +0000426 return default, [first, second]
Trent Nelson428de652008-03-18 22:41:35 +0000427
428
Victor Stinner58c07522010-11-09 01:08:59 +0000429def open(filename):
430 """Open a file in read only mode using the encoding detected by
431 detect_encoding().
432 """
Brett Cannonf3042782011-02-22 03:25:12 +0000433 buffer = builtins.open(filename, 'rb')
Victor Stinner58c07522010-11-09 01:08:59 +0000434 encoding, lines = detect_encoding(buffer.readline)
435 buffer.seek(0)
436 text = TextIOWrapper(buffer, encoding, line_buffering=True)
437 text.mode = 'r'
438 return text
439
440
Trent Nelson428de652008-03-18 22:41:35 +0000441def tokenize(readline):
442 """
443 The tokenize() generator requires one argment, readline, which
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000444 must be a callable object which provides the same interface as the
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000445 readline() method of built-in file objects. Each call to the function
Trent Nelson428de652008-03-18 22:41:35 +0000446 should return one line of input as bytes. Alternately, readline
Raymond Hettinger68c04532005-06-10 11:05:19 +0000447 can be a callable function terminating with StopIteration:
Trent Nelson428de652008-03-18 22:41:35 +0000448 readline = open(myfile, 'rb').__next__ # Example of alternate readline
Tim Peters8ac14952002-05-23 15:15:30 +0000449
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000450 The generator produces 5-tuples with these members: the token type; the
451 token string; a 2-tuple (srow, scol) of ints specifying the row and
452 column where the token begins in the source; a 2-tuple (erow, ecol) of
453 ints specifying the row and column where the token ends in the source;
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000454 and the line on which the token was found. The line passed is the
Tim Peters8ac14952002-05-23 15:15:30 +0000455 logical line; continuation lines are included.
Trent Nelson428de652008-03-18 22:41:35 +0000456
457 The first token sequence will always be an ENCODING token
458 which tells you which encoding was used to decode the bytes stream.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000459 """
Benjamin Peterson21db77e2009-11-14 16:27:26 +0000460 # This import is here to avoid problems when the itertools module is not
461 # built yet and tokenize is imported.
Benjamin Peterson81dd8b92009-11-14 18:09:17 +0000462 from itertools import chain, repeat
Trent Nelson428de652008-03-18 22:41:35 +0000463 encoding, consumed = detect_encoding(readline)
Benjamin Peterson81dd8b92009-11-14 18:09:17 +0000464 rl_gen = iter(readline, b"")
465 empty = repeat(b"")
466 return _tokenize(chain(consumed, rl_gen, empty).__next__, encoding)
Trent Nelson428de652008-03-18 22:41:35 +0000467
468
469def _tokenize(readline, encoding):
Guido van Rossum1aec3231997-04-08 14:24:39 +0000470 lnum = parenlev = continued = 0
Benjamin Peterson33856de2010-08-30 14:41:20 +0000471 numchars = '0123456789'
Guido van Rossumde655271997-04-09 17:15:54 +0000472 contstr, needcont = '', 0
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000473 contline = None
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000474 indents = [0]
Guido van Rossum1aec3231997-04-08 14:24:39 +0000475
Trent Nelson428de652008-03-18 22:41:35 +0000476 if encoding is not None:
Benjamin Peterson689a5582010-03-18 22:29:52 +0000477 if encoding == "utf-8-sig":
478 # BOM will already have been stripped.
479 encoding = "utf-8"
Raymond Hettingera48db392009-04-29 00:34:27 +0000480 yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '')
Benjamin Peterson0fe14382008-06-05 23:07:42 +0000481 while True: # loop over lines in stream
Raymond Hettinger68c04532005-06-10 11:05:19 +0000482 try:
483 line = readline()
484 except StopIteration:
Trent Nelson428de652008-03-18 22:41:35 +0000485 line = b''
486
487 if encoding is not None:
488 line = line.decode(encoding)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000489 lnum += 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000490 pos, max = 0, len(line)
491
492 if contstr: # continued string
Guido van Rossumde655271997-04-09 17:15:54 +0000493 if not line:
Collin Winterce36ad82007-08-30 01:19:48 +0000494 raise TokenError("EOF in multi-line string", strstart)
Guido van Rossum3b631771997-10-27 20:44:15 +0000495 endmatch = endprog.match(line)
496 if endmatch:
497 pos = end = endmatch.end(0)
Raymond Hettingera48db392009-04-29 00:34:27 +0000498 yield TokenInfo(STRING, contstr + line[:end],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000499 strstart, (lnum, end), contline + line)
Guido van Rossumde655271997-04-09 17:15:54 +0000500 contstr, needcont = '', 0
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000501 contline = None
Guido van Rossumde655271997-04-09 17:15:54 +0000502 elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
Raymond Hettingera48db392009-04-29 00:34:27 +0000503 yield TokenInfo(ERRORTOKEN, contstr + line,
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000504 strstart, (lnum, len(line)), contline)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000505 contstr = ''
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000506 contline = None
Guido van Rossumde655271997-04-09 17:15:54 +0000507 continue
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000508 else:
509 contstr = contstr + line
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000510 contline = contline + line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000511 continue
512
Guido van Rossum1aec3231997-04-08 14:24:39 +0000513 elif parenlev == 0 and not continued: # new statement
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000514 if not line: break
515 column = 0
Guido van Rossum1aec3231997-04-08 14:24:39 +0000516 while pos < max: # measure leading whitespace
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000517 if line[pos] == ' ':
518 column += 1
519 elif line[pos] == '\t':
520 column = (column//tabsize + 1)*tabsize
521 elif line[pos] == '\f':
522 column = 0
523 else:
524 break
525 pos += 1
526 if pos == max:
527 break
Guido van Rossum1aec3231997-04-08 14:24:39 +0000528
529 if line[pos] in '#\r\n': # skip comments or blank lines
Thomas Wouters89f507f2006-12-13 04:49:30 +0000530 if line[pos] == '#':
531 comment_token = line[pos:].rstrip('\r\n')
532 nl_pos = pos + len(comment_token)
Raymond Hettingera48db392009-04-29 00:34:27 +0000533 yield TokenInfo(COMMENT, comment_token,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000534 (lnum, pos), (lnum, pos + len(comment_token)), line)
Raymond Hettingera48db392009-04-29 00:34:27 +0000535 yield TokenInfo(NL, line[nl_pos:],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000536 (lnum, nl_pos), (lnum, len(line)), line)
537 else:
Raymond Hettingera48db392009-04-29 00:34:27 +0000538 yield TokenInfo((NL, COMMENT)[line[pos] == '#'], line[pos:],
Guido van Rossum1aec3231997-04-08 14:24:39 +0000539 (lnum, pos), (lnum, len(line)), line)
540 continue
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000541
542 if column > indents[-1]: # count indents or dedents
543 indents.append(column)
Raymond Hettingera48db392009-04-29 00:34:27 +0000544 yield TokenInfo(INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000545 while column < indents[-1]:
Raymond Hettingerda99d1c2005-06-21 07:43:58 +0000546 if column not in indents:
547 raise IndentationError(
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000548 "unindent does not match any outer indentation level",
549 ("<tokenize>", lnum, pos, line))
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000550 indents = indents[:-1]
Raymond Hettingera48db392009-04-29 00:34:27 +0000551 yield TokenInfo(DEDENT, '', (lnum, pos), (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000552
553 else: # continued statement
Guido van Rossumde655271997-04-09 17:15:54 +0000554 if not line:
Collin Winterce36ad82007-08-30 01:19:48 +0000555 raise TokenError("EOF in multi-line statement", (lnum, 0))
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000556 continued = 0
557
558 while pos < max:
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200559 pseudomatch = _compile(PseudoToken).match(line, pos)
Guido van Rossum3b631771997-10-27 20:44:15 +0000560 if pseudomatch: # scan for tokens
561 start, end = pseudomatch.span(1)
Guido van Rossumde655271997-04-09 17:15:54 +0000562 spos, epos, pos = (lnum, start), (lnum, end), end
Ezio Melotti2cc3b4b2012-11-03 17:38:43 +0200563 if start == end:
564 continue
Guido van Rossum1aec3231997-04-08 14:24:39 +0000565 token, initial = line[start:end], line[start]
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000566
Georg Brandldde00282007-03-18 19:01:53 +0000567 if (initial in numchars or # ordinary number
568 (initial == '.' and token != '.' and token != '...')):
Raymond Hettingera48db392009-04-29 00:34:27 +0000569 yield TokenInfo(NUMBER, token, spos, epos, line)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000570 elif initial in '\r\n':
Raymond Hettingera48db392009-04-29 00:34:27 +0000571 yield TokenInfo(NL if parenlev > 0 else NEWLINE,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000572 token, spos, epos, line)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000573 elif initial == '#':
Thomas Wouters89f507f2006-12-13 04:49:30 +0000574 assert not token.endswith("\n")
Raymond Hettingera48db392009-04-29 00:34:27 +0000575 yield TokenInfo(COMMENT, token, spos, epos, line)
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000576 elif token in triple_quoted:
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200577 endprog = _compile(endpats[token])
Guido van Rossum3b631771997-10-27 20:44:15 +0000578 endmatch = endprog.match(line, pos)
579 if endmatch: # all on one line
580 pos = endmatch.end(0)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000581 token = line[start:pos]
Raymond Hettingera48db392009-04-29 00:34:27 +0000582 yield TokenInfo(STRING, token, spos, (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000583 else:
Guido van Rossum1aec3231997-04-08 14:24:39 +0000584 strstart = (lnum, start) # multiple lines
585 contstr = line[start:]
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000586 contline = line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000587 break
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000588 elif initial in single_quoted or \
589 token[:2] in single_quoted or \
590 token[:3] in single_quoted:
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000591 if token[-1] == '\n': # continued string
Guido van Rossum1aec3231997-04-08 14:24:39 +0000592 strstart = (lnum, start)
Antoine Pitrou10a99b02011-10-11 15:45:56 +0200593 endprog = _compile(endpats[initial] or
594 endpats[token[1]] or
595 endpats[token[2]])
Guido van Rossumde655271997-04-09 17:15:54 +0000596 contstr, needcont = line[start:], 1
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000597 contline = line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000598 break
599 else: # ordinary string
Raymond Hettingera48db392009-04-29 00:34:27 +0000600 yield TokenInfo(STRING, token, spos, epos, line)
Benjamin Peterson33856de2010-08-30 14:41:20 +0000601 elif initial.isidentifier(): # ordinary name
Raymond Hettingera48db392009-04-29 00:34:27 +0000602 yield TokenInfo(NAME, token, spos, epos, line)
Guido van Rossum3b631771997-10-27 20:44:15 +0000603 elif initial == '\\': # continued stmt
604 continued = 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000605 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000606 if initial in '([{':
607 parenlev += 1
608 elif initial in ')]}':
609 parenlev -= 1
Raymond Hettingera48db392009-04-29 00:34:27 +0000610 yield TokenInfo(OP, token, spos, epos, line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000611 else:
Raymond Hettingera48db392009-04-29 00:34:27 +0000612 yield TokenInfo(ERRORTOKEN, line[pos],
Guido van Rossumde655271997-04-09 17:15:54 +0000613 (lnum, pos), (lnum, pos+1), line)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000614 pos += 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000615
616 for indent in indents[1:]: # pop remaining indent levels
Raymond Hettingera48db392009-04-29 00:34:27 +0000617 yield TokenInfo(DEDENT, '', (lnum, 0), (lnum, 0), '')
618 yield TokenInfo(ENDMARKER, '', (lnum, 0), (lnum, 0), '')
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000619
Trent Nelson428de652008-03-18 22:41:35 +0000620
621# An undocumented, backwards compatible, API for all the places in the standard
622# library that expect to be able to use tokenize with strings
623def generate_tokens(readline):
624 return _tokenize(readline, None)
Raymond Hettinger6c60d092010-09-09 04:32:39 +0000625
Meador Inge14c0f032011-10-07 08:53:38 -0500626def main():
627 import argparse
628
629 # Helper error handling routines
630 def perror(message):
631 print(message, file=sys.stderr)
632
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
643 # Parse the arguments and options
644 parser = argparse.ArgumentParser(prog='python -m tokenize')
645 parser.add_argument(dest='filename', nargs='?',
646 metavar='filename.py',
647 help='the file to tokenize; defaults to stdin')
Meador Inge00c7f852012-01-19 00:44:45 -0600648 parser.add_argument('-e', '--exact', dest='exact', action='store_true',
649 help='display token names using the exact type')
Meador Inge14c0f032011-10-07 08:53:38 -0500650 args = parser.parse_args()
651
652 try:
653 # Tokenize the input
654 if args.filename:
655 filename = args.filename
656 with builtins.open(filename, 'rb') as f:
657 tokens = list(tokenize(f.readline))
658 else:
659 filename = "<stdin>"
660 tokens = _tokenize(sys.stdin.readline, None)
661
662 # Output the tokenization
663 for token in tokens:
Meador Inge00c7f852012-01-19 00:44:45 -0600664 token_type = token.type
665 if args.exact:
666 token_type = token.exact_type
Meador Inge14c0f032011-10-07 08:53:38 -0500667 token_range = "%d,%d-%d,%d:" % (token.start + token.end)
668 print("%-20s%-15s%-15r" %
Meador Inge00c7f852012-01-19 00:44:45 -0600669 (token_range, tok_name[token_type], token.string))
Meador Inge14c0f032011-10-07 08:53:38 -0500670 except IndentationError as err:
671 line, column = err.args[1][1:3]
672 error(err.args[0], filename, (line, column))
673 except TokenError as err:
674 line, column = err.args[1]
675 error(err.args[0], filename, (line, column))
676 except SyntaxError as err:
677 error(err, filename)
678 except IOError as err:
679 error(err)
680 except KeyboardInterrupt:
681 print("interrupted\n")
682 except Exception as err:
683 perror("unexpected error: %s" % err)
684 raise
685
Raymond Hettinger6c60d092010-09-09 04:32:39 +0000686if __name__ == "__main__":
Meador Inge14c0f032011-10-07 08:53:38 -0500687 main()