blob: 59081d3579082dcf38b26a1181d8a805e9657c8f [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 Cannon45b96d32011-02-22 03:35:18 +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
Trent Nelson428de652008-03-18 22:41:35 +000034cookie_re = re.compile("coding[:=]\s*([-\w.]+)")
Guido van Rossum4d8e8591992-01-01 19:34:47 +000035
Skip Montanaro40fc1602001-03-01 04:27:19 +000036import token
Alexander Belopolskyb9d10d02010-11-11 14:07:41 +000037__all__ = token.__all__ + ["COMMENT", "tokenize", "detect_encoding",
38 "NL", "untokenize", "ENCODING", "TokenInfo"]
Skip Montanaro40fc1602001-03-01 04:27:19 +000039del token
40
Guido van Rossum1aec3231997-04-08 14:24:39 +000041COMMENT = N_TOKENS
42tok_name[COMMENT] = 'COMMENT'
Guido van Rossuma90c78b1998-04-03 16:05:38 +000043NL = N_TOKENS + 1
44tok_name[NL] = 'NL'
Trent Nelson428de652008-03-18 22:41:35 +000045ENCODING = N_TOKENS + 2
46tok_name[ENCODING] = 'ENCODING'
47N_TOKENS += 3
Guido van Rossum1aec3231997-04-08 14:24:39 +000048
Raymond Hettinger3fb79c72010-09-09 07:15:18 +000049class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
Raymond Hettingeraa17a7f2009-04-29 14:21:25 +000050 def __repr__(self):
Raymond Hettingera0e79402010-09-09 08:29:05 +000051 annotated_type = '%d (%s)' % (self.type, tok_name[self.type])
52 return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' %
53 self._replace(type=annotated_type))
Raymond Hettingeraa17a7f2009-04-29 14:21:25 +000054
Eric S. Raymondb08b2d32001-02-09 11:10:16 +000055def group(*choices): return '(' + '|'.join(choices) + ')'
Guido van Rossum68468eb2003-02-27 20:14:51 +000056def any(*choices): return group(*choices) + '*'
57def maybe(*choices): return group(*choices) + '?'
Guido van Rossum4d8e8591992-01-01 19:34:47 +000058
Antoine Pitroufd036452008-08-19 17:56:33 +000059# Note: we use unicode matching for names ("\w") but ascii matching for
60# number literals.
Guido van Rossum3b631771997-10-27 20:44:15 +000061Whitespace = r'[ \f\t]*'
62Comment = r'#[^\r\n]*'
63Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
Benjamin Peterson33856de2010-08-30 14:41:20 +000064Name = r'\w+'
Guido van Rossum4d8e8591992-01-01 19:34:47 +000065
Antoine Pitroufd036452008-08-19 17:56:33 +000066Hexnumber = r'0[xX][0-9a-fA-F]+'
Georg Brandlfceab5a2008-01-19 20:08:23 +000067Binnumber = r'0[bB][01]+'
68Octnumber = r'0[oO][0-7]+'
Antoine Pitroufd036452008-08-19 17:56:33 +000069Decnumber = r'(?:0+|[1-9][0-9]*)'
Guido van Rossumcd16bf62007-06-13 18:07:49 +000070Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
Antoine Pitroufd036452008-08-19 17:56:33 +000071Exponent = r'[eE][-+]?[0-9]+'
72Pointfloat = group(r'[0-9]+\.[0-9]*', r'\.[0-9]+') + maybe(Exponent)
73Expfloat = r'[0-9]+' + Exponent
Guido van Rossum1aec3231997-04-08 14:24:39 +000074Floatnumber = group(Pointfloat, Expfloat)
Antoine Pitroufd036452008-08-19 17:56:33 +000075Imagnumber = group(r'[0-9]+[jJ]', Floatnumber + r'[jJ]')
Guido van Rossum1aec3231997-04-08 14:24:39 +000076Number = group(Imagnumber, Floatnumber, Intnumber)
Guido van Rossum4d8e8591992-01-01 19:34:47 +000077
Tim Petersde495832000-10-07 05:09:39 +000078# Tail end of ' string.
79Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
80# Tail end of " string.
81Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
82# Tail end of ''' string.
83Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
84# Tail end of """ string.
85Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
Guido van Rossum4fe72f92007-11-12 17:40:10 +000086Triple = group("[bB]?[rR]?'''", '[bB]?[rR]?"""')
Tim Petersde495832000-10-07 05:09:39 +000087# Single-line ' or " string.
Guido van Rossum4fe72f92007-11-12 17:40:10 +000088String = group(r"[bB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
89 r'[bB]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
Guido van Rossum4d8e8591992-01-01 19:34:47 +000090
Tim Petersde495832000-10-07 05:09:39 +000091# Because of leftmost-then-longest match semantics, be sure to put the
92# longest operators first (e.g., if = came before ==, == would get
93# recognized as two instances of =).
Guido van Rossumb053cd82006-08-24 03:53:23 +000094Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=",
Neal Norwitzc1505362006-12-28 06:47:50 +000095 r"//=?", r"->",
Tim Petersde495832000-10-07 05:09:39 +000096 r"[+\-*/%&|^=<>]=?",
97 r"~")
Thomas Wouterse1519a12000-08-24 21:44:52 +000098
Guido van Rossum4d8e8591992-01-01 19:34:47 +000099Bracket = '[][(){}]'
Georg Brandldde00282007-03-18 19:01:53 +0000100Special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]')
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000101Funny = group(Operator, Bracket, Special)
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000102
Guido van Rossum3b631771997-10-27 20:44:15 +0000103PlainToken = group(Number, Funny, String, Name)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000104Token = Ignore + PlainToken
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000105
Tim Petersde495832000-10-07 05:09:39 +0000106# First (or only) line of ' or " string.
Guido van Rossum4fe72f92007-11-12 17:40:10 +0000107ContStr = group(r"[bB]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
Ka-Ping Yee1ff08b12001-01-15 22:04:30 +0000108 group("'", r'\\\r?\n'),
Guido van Rossum4fe72f92007-11-12 17:40:10 +0000109 r'[bB]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
Ka-Ping Yee1ff08b12001-01-15 22:04:30 +0000110 group('"', r'\\\r?\n'))
Guido van Rossum3b631771997-10-27 20:44:15 +0000111PseudoExtras = group(r'\\\r?\n', Comment, Triple)
112PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000113
Benjamin Peterson33856de2010-08-30 14:41:20 +0000114def _compile(expr):
115 return re.compile(expr, re.UNICODE)
116
Guido van Rossum3b631771997-10-27 20:44:15 +0000117tokenprog, pseudoprog, single3prog, double3prog = map(
Benjamin Peterson33856de2010-08-30 14:41:20 +0000118 _compile, (Token, PseudoToken, Single3, Double3))
119endprogs = {"'": _compile(Single), '"': _compile(Double),
Guido van Rossum3b631771997-10-27 20:44:15 +0000120 "'''": single3prog, '"""': double3prog,
Guido van Rossumfefc9221997-10-27 21:17:24 +0000121 "r'''": single3prog, 'r"""': double3prog,
Guido van Rossum4fe72f92007-11-12 17:40:10 +0000122 "b'''": single3prog, 'b"""': double3prog,
123 "br'''": single3prog, 'br"""': double3prog,
Ka-Ping Yee1ff08b12001-01-15 22:04:30 +0000124 "R'''": single3prog, 'R"""': double3prog,
Guido van Rossum4fe72f92007-11-12 17:40:10 +0000125 "B'''": single3prog, 'B"""': double3prog,
126 "bR'''": single3prog, 'bR"""': double3prog,
127 "Br'''": single3prog, 'Br"""': double3prog,
128 "BR'''": single3prog, 'BR"""': double3prog,
129 'r': None, 'R': None, 'b': None, 'B': None}
Guido van Rossum4d8e8591992-01-01 19:34:47 +0000130
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000131triple_quoted = {}
132for t in ("'''", '"""',
133 "r'''", 'r"""', "R'''", 'R"""',
Guido van Rossum4fe72f92007-11-12 17:40:10 +0000134 "b'''", 'b"""', "B'''", 'B"""',
135 "br'''", 'br"""', "Br'''", 'Br"""',
136 "bR'''", 'bR"""', "BR'''", 'BR"""'):
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000137 triple_quoted[t] = t
138single_quoted = {}
139for t in ("'", '"',
140 "r'", 'r"', "R'", 'R"',
Guido van Rossum4fe72f92007-11-12 17:40:10 +0000141 "b'", 'b"', "B'", 'B"',
142 "br'", 'br"', "Br'", 'Br"',
143 "bR'", 'bR"', "BR'", 'BR"' ):
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000144 single_quoted[t] = t
145
Benjamin Peterson33856de2010-08-30 14:41:20 +0000146del _compile
147
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000148tabsize = 8
Fred Drake9b8d8012000-08-17 04:45:13 +0000149
Ka-Ping Yee28c62bb2001-03-23 05:22:49 +0000150class TokenError(Exception): pass
151
152class StopTokenizing(Exception): pass
Fred Drake9b8d8012000-08-17 04:45:13 +0000153
Tim Peters5ca576e2001-06-18 22:08:13 +0000154
Thomas Wouters89f507f2006-12-13 04:49:30 +0000155class Untokenizer:
156
157 def __init__(self):
158 self.tokens = []
159 self.prev_row = 1
160 self.prev_col = 0
Trent Nelson428de652008-03-18 22:41:35 +0000161 self.encoding = None
Thomas Wouters89f507f2006-12-13 04:49:30 +0000162
163 def add_whitespace(self, start):
164 row, col = start
165 assert row <= self.prev_row
166 col_offset = col - self.prev_col
167 if col_offset:
168 self.tokens.append(" " * col_offset)
169
170 def untokenize(self, iterable):
171 for t in iterable:
172 if len(t) == 2:
173 self.compat(t, iterable)
174 break
175 tok_type, token, start, end, line = t
Trent Nelson428de652008-03-18 22:41:35 +0000176 if tok_type == ENCODING:
177 self.encoding = token
178 continue
Thomas Wouters89f507f2006-12-13 04:49:30 +0000179 self.add_whitespace(start)
180 self.tokens.append(token)
181 self.prev_row, self.prev_col = end
182 if tok_type in (NEWLINE, NL):
183 self.prev_row += 1
184 self.prev_col = 0
185 return "".join(self.tokens)
186
187 def compat(self, token, iterable):
188 startline = False
189 indents = []
190 toks_append = self.tokens.append
191 toknum, tokval = token
Trent Nelson428de652008-03-18 22:41:35 +0000192
Thomas Wouters89f507f2006-12-13 04:49:30 +0000193 if toknum in (NAME, NUMBER):
194 tokval += ' '
195 if toknum in (NEWLINE, NL):
196 startline = True
Christian Heimesba4af492008-03-28 00:55:15 +0000197 prevstring = False
Thomas Wouters89f507f2006-12-13 04:49:30 +0000198 for tok in iterable:
199 toknum, tokval = tok[:2]
Trent Nelson428de652008-03-18 22:41:35 +0000200 if toknum == ENCODING:
201 self.encoding = tokval
202 continue
Thomas Wouters89f507f2006-12-13 04:49:30 +0000203
204 if toknum in (NAME, NUMBER):
205 tokval += ' '
206
Christian Heimesba4af492008-03-28 00:55:15 +0000207 # Insert a space between two consecutive strings
208 if toknum == STRING:
209 if prevstring:
210 tokval = ' ' + tokval
211 prevstring = True
212 else:
213 prevstring = False
214
Thomas Wouters89f507f2006-12-13 04:49:30 +0000215 if toknum == INDENT:
216 indents.append(tokval)
217 continue
218 elif toknum == DEDENT:
219 indents.pop()
220 continue
221 elif toknum in (NEWLINE, NL):
222 startline = True
223 elif startline and indents:
224 toks_append(indents[-1])
225 startline = False
226 toks_append(tokval)
Raymond Hettinger68c04532005-06-10 11:05:19 +0000227
Trent Nelson428de652008-03-18 22:41:35 +0000228
Raymond Hettinger68c04532005-06-10 11:05:19 +0000229def untokenize(iterable):
230 """Transform tokens back into Python source code.
Trent Nelson428de652008-03-18 22:41:35 +0000231 It returns a bytes object, encoded using the ENCODING
232 token, which is the first token sequence output by tokenize.
Raymond Hettinger68c04532005-06-10 11:05:19 +0000233
234 Each element returned by the iterable must be a token sequence
Thomas Wouters89f507f2006-12-13 04:49:30 +0000235 with at least two elements, a token number and token value. If
236 only two tokens are passed, the resulting output is poor.
Raymond Hettinger68c04532005-06-10 11:05:19 +0000237
Thomas Wouters89f507f2006-12-13 04:49:30 +0000238 Round-trip invariant for full input:
239 Untokenized source will match input source exactly
240
241 Round-trip invariant for limited intput:
Trent Nelson428de652008-03-18 22:41:35 +0000242 # Output bytes will tokenize the back to the input
243 t1 = [tok[:2] for tok in tokenize(f.readline)]
Raymond Hettinger68c04532005-06-10 11:05:19 +0000244 newcode = untokenize(t1)
Trent Nelson428de652008-03-18 22:41:35 +0000245 readline = BytesIO(newcode).readline
246 t2 = [tok[:2] for tok in tokenize(readline)]
Raymond Hettinger68c04532005-06-10 11:05:19 +0000247 assert t1 == t2
248 """
Thomas Wouters89f507f2006-12-13 04:49:30 +0000249 ut = Untokenizer()
Trent Nelson428de652008-03-18 22:41:35 +0000250 out = ut.untokenize(iterable)
251 if ut.encoding is not None:
252 out = out.encode(ut.encoding)
253 return out
Raymond Hettinger68c04532005-06-10 11:05:19 +0000254
Trent Nelson428de652008-03-18 22:41:35 +0000255
Benjamin Petersond3afada2009-10-09 21:43:09 +0000256def _get_normal_name(orig_enc):
257 """Imitates get_normal_name in tokenizer.c."""
258 # Only care about the first 12 characters.
259 enc = orig_enc[:12].lower().replace("_", "-")
260 if enc == "utf-8" or enc.startswith("utf-8-"):
261 return "utf-8"
262 if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
263 enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
264 return "iso-8859-1"
265 return orig_enc
266
Trent Nelson428de652008-03-18 22:41:35 +0000267def detect_encoding(readline):
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000268 """
Trent Nelson428de652008-03-18 22:41:35 +0000269 The detect_encoding() function is used to detect the encoding that should
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000270 be used to decode a Python source file. It requires one argment, readline,
Trent Nelson428de652008-03-18 22:41:35 +0000271 in the same way as the tokenize() generator.
272
273 It will call readline a maximum of twice, and return the encoding used
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000274 (as a string) and a list of any lines (left as bytes) it has read in.
Trent Nelson428de652008-03-18 22:41:35 +0000275
276 It detects the encoding from the presence of a utf-8 bom or an encoding
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000277 cookie as specified in pep-0263. If both a bom and a cookie are present,
278 but disagree, a SyntaxError will be raised. If the encoding cookie is an
279 invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
Benjamin Peterson689a5582010-03-18 22:29:52 +0000280 'utf-8-sig' is returned.
Trent Nelson428de652008-03-18 22:41:35 +0000281
282 If no encoding is specified, then the default of 'utf-8' will be returned.
283 """
Trent Nelson428de652008-03-18 22:41:35 +0000284 bom_found = False
285 encoding = None
Benjamin Peterson689a5582010-03-18 22:29:52 +0000286 default = 'utf-8'
Trent Nelson428de652008-03-18 22:41:35 +0000287 def read_or_stop():
288 try:
289 return readline()
290 except StopIteration:
291 return b''
292
293 def find_cookie(line):
294 try:
Martin v. Löwis63674f42012-04-20 14:36:47 +0200295 # Decode as UTF-8. Either the line is an encoding declaration,
296 # in which case it should be pure ASCII, or it must be UTF-8
297 # per default encoding.
298 line_string = line.decode('utf-8')
Trent Nelson428de652008-03-18 22:41:35 +0000299 except UnicodeDecodeError:
Martin v. Löwis63674f42012-04-20 14:36:47 +0200300 raise SyntaxError("invalid or missing encoding declaration")
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000301
302 matches = cookie_re.findall(line_string)
303 if not matches:
304 return None
Benjamin Petersond3afada2009-10-09 21:43:09 +0000305 encoding = _get_normal_name(matches[0])
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000306 try:
307 codec = lookup(encoding)
308 except LookupError:
309 # This behaviour mimics the Python interpreter
310 raise SyntaxError("unknown encoding: " + encoding)
311
Benjamin Peterson1613ed82010-03-18 22:34:15 +0000312 if bom_found:
Florent Xicluna11f0b412012-07-07 12:13:35 +0200313 if encoding != 'utf-8':
Benjamin Peterson1613ed82010-03-18 22:34:15 +0000314 # This behaviour mimics the Python interpreter
315 raise SyntaxError('encoding problem: utf-8')
316 encoding += '-sig'
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000317 return encoding
Trent Nelson428de652008-03-18 22:41:35 +0000318
319 first = read_or_stop()
Benjamin Peterson433f32c2008-12-12 01:25:05 +0000320 if first.startswith(BOM_UTF8):
Trent Nelson428de652008-03-18 22:41:35 +0000321 bom_found = True
322 first = first[3:]
Benjamin Peterson689a5582010-03-18 22:29:52 +0000323 default = 'utf-8-sig'
Trent Nelson428de652008-03-18 22:41:35 +0000324 if not first:
Benjamin Peterson689a5582010-03-18 22:29:52 +0000325 return default, []
Trent Nelson428de652008-03-18 22:41:35 +0000326
327 encoding = find_cookie(first)
328 if encoding:
329 return encoding, [first]
330
331 second = read_or_stop()
332 if not second:
Benjamin Peterson689a5582010-03-18 22:29:52 +0000333 return default, [first]
Trent Nelson428de652008-03-18 22:41:35 +0000334
335 encoding = find_cookie(second)
336 if encoding:
337 return encoding, [first, second]
338
Benjamin Peterson689a5582010-03-18 22:29:52 +0000339 return default, [first, second]
Trent Nelson428de652008-03-18 22:41:35 +0000340
341
Victor Stinner58c07522010-11-09 01:08:59 +0000342def open(filename):
343 """Open a file in read only mode using the encoding detected by
344 detect_encoding().
345 """
Brett Cannon45b96d32011-02-22 03:35:18 +0000346 buffer = builtins.open(filename, 'rb')
Victor Stinner58c07522010-11-09 01:08:59 +0000347 encoding, lines = detect_encoding(buffer.readline)
348 buffer.seek(0)
349 text = TextIOWrapper(buffer, encoding, line_buffering=True)
350 text.mode = 'r'
351 return text
352
353
Trent Nelson428de652008-03-18 22:41:35 +0000354def tokenize(readline):
355 """
356 The tokenize() generator requires one argment, readline, which
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000357 must be a callable object which provides the same interface as the
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000358 readline() method of built-in file objects. Each call to the function
Trent Nelson428de652008-03-18 22:41:35 +0000359 should return one line of input as bytes. Alternately, readline
Raymond Hettinger68c04532005-06-10 11:05:19 +0000360 can be a callable function terminating with StopIteration:
Trent Nelson428de652008-03-18 22:41:35 +0000361 readline = open(myfile, 'rb').__next__ # Example of alternate readline
Tim Peters8ac14952002-05-23 15:15:30 +0000362
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000363 The generator produces 5-tuples with these members: the token type; the
364 token string; a 2-tuple (srow, scol) of ints specifying the row and
365 column where the token begins in the source; a 2-tuple (erow, ecol) of
366 ints specifying the row and column where the token ends in the source;
Florent Xicluna43e4ea12010-09-03 19:54:02 +0000367 and the line on which the token was found. The line passed is the
Tim Peters8ac14952002-05-23 15:15:30 +0000368 logical line; continuation lines are included.
Trent Nelson428de652008-03-18 22:41:35 +0000369
370 The first token sequence will always be an ENCODING token
371 which tells you which encoding was used to decode the bytes stream.
Raymond Hettingerd1fa3db2002-05-15 02:56:03 +0000372 """
Benjamin Peterson21db77e2009-11-14 16:27:26 +0000373 # This import is here to avoid problems when the itertools module is not
374 # built yet and tokenize is imported.
Benjamin Peterson81dd8b92009-11-14 18:09:17 +0000375 from itertools import chain, repeat
Trent Nelson428de652008-03-18 22:41:35 +0000376 encoding, consumed = detect_encoding(readline)
Benjamin Peterson81dd8b92009-11-14 18:09:17 +0000377 rl_gen = iter(readline, b"")
378 empty = repeat(b"")
379 return _tokenize(chain(consumed, rl_gen, empty).__next__, encoding)
Trent Nelson428de652008-03-18 22:41:35 +0000380
381
382def _tokenize(readline, encoding):
Guido van Rossum1aec3231997-04-08 14:24:39 +0000383 lnum = parenlev = continued = 0
Benjamin Peterson33856de2010-08-30 14:41:20 +0000384 numchars = '0123456789'
Guido van Rossumde655271997-04-09 17:15:54 +0000385 contstr, needcont = '', 0
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000386 contline = None
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000387 indents = [0]
Guido van Rossum1aec3231997-04-08 14:24:39 +0000388
Trent Nelson428de652008-03-18 22:41:35 +0000389 if encoding is not None:
Benjamin Peterson689a5582010-03-18 22:29:52 +0000390 if encoding == "utf-8-sig":
391 # BOM will already have been stripped.
392 encoding = "utf-8"
Raymond Hettingera48db392009-04-29 00:34:27 +0000393 yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '')
Benjamin Peterson0fe14382008-06-05 23:07:42 +0000394 while True: # loop over lines in stream
Raymond Hettinger68c04532005-06-10 11:05:19 +0000395 try:
396 line = readline()
397 except StopIteration:
Trent Nelson428de652008-03-18 22:41:35 +0000398 line = b''
399
400 if encoding is not None:
401 line = line.decode(encoding)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000402 lnum += 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000403 pos, max = 0, len(line)
404
405 if contstr: # continued string
Guido van Rossumde655271997-04-09 17:15:54 +0000406 if not line:
Collin Winterce36ad82007-08-30 01:19:48 +0000407 raise TokenError("EOF in multi-line string", strstart)
Guido van Rossum3b631771997-10-27 20:44:15 +0000408 endmatch = endprog.match(line)
409 if endmatch:
410 pos = end = endmatch.end(0)
Raymond Hettingera48db392009-04-29 00:34:27 +0000411 yield TokenInfo(STRING, contstr + line[:end],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000412 strstart, (lnum, end), contline + line)
Guido van Rossumde655271997-04-09 17:15:54 +0000413 contstr, needcont = '', 0
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000414 contline = None
Guido van Rossumde655271997-04-09 17:15:54 +0000415 elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
Raymond Hettingera48db392009-04-29 00:34:27 +0000416 yield TokenInfo(ERRORTOKEN, contstr + line,
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000417 strstart, (lnum, len(line)), contline)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000418 contstr = ''
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000419 contline = None
Guido van Rossumde655271997-04-09 17:15:54 +0000420 continue
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000421 else:
422 contstr = contstr + line
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000423 contline = contline + line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000424 continue
425
Guido van Rossum1aec3231997-04-08 14:24:39 +0000426 elif parenlev == 0 and not continued: # new statement
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000427 if not line: break
428 column = 0
Guido van Rossum1aec3231997-04-08 14:24:39 +0000429 while pos < max: # measure leading whitespace
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000430 if line[pos] == ' ':
431 column += 1
432 elif line[pos] == '\t':
433 column = (column//tabsize + 1)*tabsize
434 elif line[pos] == '\f':
435 column = 0
436 else:
437 break
438 pos += 1
439 if pos == max:
440 break
Guido van Rossum1aec3231997-04-08 14:24:39 +0000441
442 if line[pos] in '#\r\n': # skip comments or blank lines
Thomas Wouters89f507f2006-12-13 04:49:30 +0000443 if line[pos] == '#':
444 comment_token = line[pos:].rstrip('\r\n')
445 nl_pos = pos + len(comment_token)
Raymond Hettingera48db392009-04-29 00:34:27 +0000446 yield TokenInfo(COMMENT, comment_token,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000447 (lnum, pos), (lnum, pos + len(comment_token)), line)
Raymond Hettingera48db392009-04-29 00:34:27 +0000448 yield TokenInfo(NL, line[nl_pos:],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000449 (lnum, nl_pos), (lnum, len(line)), line)
450 else:
Raymond Hettingera48db392009-04-29 00:34:27 +0000451 yield TokenInfo((NL, COMMENT)[line[pos] == '#'], line[pos:],
Guido van Rossum1aec3231997-04-08 14:24:39 +0000452 (lnum, pos), (lnum, len(line)), line)
453 continue
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000454
455 if column > indents[-1]: # count indents or dedents
456 indents.append(column)
Raymond Hettingera48db392009-04-29 00:34:27 +0000457 yield TokenInfo(INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000458 while column < indents[-1]:
Raymond Hettingerda99d1c2005-06-21 07:43:58 +0000459 if column not in indents:
460 raise IndentationError(
Thomas Wouters00ee7ba2006-08-21 19:07:27 +0000461 "unindent does not match any outer indentation level",
462 ("<tokenize>", lnum, pos, line))
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000463 indents = indents[:-1]
Raymond Hettingera48db392009-04-29 00:34:27 +0000464 yield TokenInfo(DEDENT, '', (lnum, pos), (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000465
466 else: # continued statement
Guido van Rossumde655271997-04-09 17:15:54 +0000467 if not line:
Collin Winterce36ad82007-08-30 01:19:48 +0000468 raise TokenError("EOF in multi-line statement", (lnum, 0))
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000469 continued = 0
470
471 while pos < max:
Guido van Rossum3b631771997-10-27 20:44:15 +0000472 pseudomatch = pseudoprog.match(line, pos)
473 if pseudomatch: # scan for tokens
474 start, end = pseudomatch.span(1)
Guido van Rossumde655271997-04-09 17:15:54 +0000475 spos, epos, pos = (lnum, start), (lnum, end), end
Guido van Rossum1aec3231997-04-08 14:24:39 +0000476 token, initial = line[start:end], line[start]
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000477
Georg Brandldde00282007-03-18 19:01:53 +0000478 if (initial in numchars or # ordinary number
479 (initial == '.' and token != '.' and token != '...')):
Raymond Hettingera48db392009-04-29 00:34:27 +0000480 yield TokenInfo(NUMBER, token, spos, epos, line)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000481 elif initial in '\r\n':
Raymond Hettingera48db392009-04-29 00:34:27 +0000482 yield TokenInfo(NL if parenlev > 0 else NEWLINE,
Thomas Wouters89f507f2006-12-13 04:49:30 +0000483 token, spos, epos, line)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000484 elif initial == '#':
Thomas Wouters89f507f2006-12-13 04:49:30 +0000485 assert not token.endswith("\n")
Raymond Hettingera48db392009-04-29 00:34:27 +0000486 yield TokenInfo(COMMENT, token, spos, epos, line)
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000487 elif token in triple_quoted:
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000488 endprog = endprogs[token]
Guido van Rossum3b631771997-10-27 20:44:15 +0000489 endmatch = endprog.match(line, pos)
490 if endmatch: # all on one line
491 pos = endmatch.end(0)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000492 token = line[start:pos]
Raymond Hettingera48db392009-04-29 00:34:27 +0000493 yield TokenInfo(STRING, token, spos, (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000494 else:
Guido van Rossum1aec3231997-04-08 14:24:39 +0000495 strstart = (lnum, start) # multiple lines
496 contstr = line[start:]
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000497 contline = line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000498 break
Guido van Rossum9d6897a2002-08-24 06:54:19 +0000499 elif initial in single_quoted or \
500 token[:2] in single_quoted or \
501 token[:3] in single_quoted:
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000502 if token[-1] == '\n': # continued string
Guido van Rossum1aec3231997-04-08 14:24:39 +0000503 strstart = (lnum, start)
Ka-Ping Yee1ff08b12001-01-15 22:04:30 +0000504 endprog = (endprogs[initial] or endprogs[token[1]] or
505 endprogs[token[2]])
Guido van Rossumde655271997-04-09 17:15:54 +0000506 contstr, needcont = line[start:], 1
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000507 contline = line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000508 break
509 else: # ordinary string
Raymond Hettingera48db392009-04-29 00:34:27 +0000510 yield TokenInfo(STRING, token, spos, epos, line)
Benjamin Peterson33856de2010-08-30 14:41:20 +0000511 elif initial.isidentifier(): # ordinary name
Raymond Hettingera48db392009-04-29 00:34:27 +0000512 yield TokenInfo(NAME, token, spos, epos, line)
Guido van Rossum3b631771997-10-27 20:44:15 +0000513 elif initial == '\\': # continued stmt
514 continued = 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000515 else:
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000516 if initial in '([{':
517 parenlev += 1
518 elif initial in ')]}':
519 parenlev -= 1
Raymond Hettingera48db392009-04-29 00:34:27 +0000520 yield TokenInfo(OP, token, spos, epos, line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000521 else:
Raymond Hettingera48db392009-04-29 00:34:27 +0000522 yield TokenInfo(ERRORTOKEN, line[pos],
Guido van Rossumde655271997-04-09 17:15:54 +0000523 (lnum, pos), (lnum, pos+1), line)
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000524 pos += 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000525
526 for indent in indents[1:]: # pop remaining indent levels
Raymond Hettingera48db392009-04-29 00:34:27 +0000527 yield TokenInfo(DEDENT, '', (lnum, 0), (lnum, 0), '')
528 yield TokenInfo(ENDMARKER, '', (lnum, 0), (lnum, 0), '')
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000529
Trent Nelson428de652008-03-18 22:41:35 +0000530
531# An undocumented, backwards compatible, API for all the places in the standard
532# library that expect to be able to use tokenize with strings
533def generate_tokens(readline):
534 return _tokenize(readline, None)
Raymond Hettinger6c60d092010-09-09 04:32:39 +0000535
536if __name__ == "__main__":
537 # Quick sanity check
538 s = b'''def parseline(self, line):
539 """Parse the line into a command name and a string containing
540 the arguments. Returns a tuple containing (command, args, line).
541 'command' and 'args' may be None if the line couldn't be parsed.
542 """
543 line = line.strip()
544 if not line:
545 return None, None, line
546 elif line[0] == '?':
547 line = 'help ' + line[1:]
548 elif line[0] == '!':
549 if hasattr(self, 'do_shell'):
550 line = 'shell ' + line[1:]
551 else:
552 return None, None, line
553 i, n = 0, len(line)
554 while i < n and line[i] in self.identchars: i = i+1
555 cmd, arg = line[:i], line[i:].strip()
556 return cmd, arg, line
557 '''
558 for tok in tokenize(iter(s.splitlines()).__next__):
559 print(tok)