blob: f2ba0a28a1151ef5117f48ba9d72ab9b0d0a7817 [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
Guido van Rossum1aec3231997-04-08 14:24:39 +00003This module exports a function called 'tokenize()' that breaks a stream of
4text into Python tokens. It accepts a readline-like method which is called
5repeatedly to get the next line of input (or "" for EOF) and a "token-eater"
6function which is called once for each token found. The latter function is
7passed the token type, a string containing the token, the starting and
8ending (row, column) coordinates of the token, and the original line. It is
9designed to match the working of the Python tokenizer exactly, except that
Guido van Rossum3b631771997-10-27 20:44:15 +000010it produces COMMENT tokens for comments and gives type OP for all operators."""
Guido van Rossumb51eaa11997-03-07 00:21:55 +000011
Guido van Rossuma90c78b1998-04-03 16:05:38 +000012__version__ = "Ka-Ping Yee, 26 October 1997; patched, GvR 3/30/98"
Guido van Rossumb51eaa11997-03-07 00:21:55 +000013
Guido van Rossum3b631771997-10-27 20:44:15 +000014import string, re
Guido van Rossumfc6f5331997-03-07 00:21:12 +000015from token import *
Guido van Rossum4d8e8591992-01-01 19:34:47 +000016
Guido van Rossum1aec3231997-04-08 14:24:39 +000017COMMENT = N_TOKENS
18tok_name[COMMENT] = 'COMMENT'
Guido van Rossuma90c78b1998-04-03 16:05:38 +000019NL = N_TOKENS + 1
20tok_name[NL] = 'NL'
21
Guido van Rossum1aec3231997-04-08 14:24:39 +000022
23# Changes from 1.3:
24# Ignore now accepts \f as whitespace. Operator now includes '**'.
25# Ignore and Special now accept \n or \r\n at the end of a line.
26# Imagnumber is new. Expfloat is corrected to reject '0e4'.
Guido van Rossum3b631771997-10-27 20:44:15 +000027# Note: to quote a backslash in a regex, it must be doubled in a r'aw' string.
Guido van Rossum1aec3231997-04-08 14:24:39 +000028
Guido van Rossum3b631771997-10-27 20:44:15 +000029def group(*choices): return '(' + string.join(choices, '|') + ')'
30def any(*choices): return apply(group, choices) + '*'
31def maybe(*choices): return apply(group, choices) + '?'
Guido van Rossum4d8e8591992-01-01 19:34:47 +000032
Guido van Rossum3b631771997-10-27 20:44:15 +000033Whitespace = r'[ \f\t]*'
34Comment = r'#[^\r\n]*'
35Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
36Name = r'[a-zA-Z_]\w*'
Guido van Rossum4d8e8591992-01-01 19:34:47 +000037
Guido van Rossum3b631771997-10-27 20:44:15 +000038Hexnumber = r'0[xX][\da-fA-F]*[lL]?'
39Octnumber = r'0[0-7]*[lL]?'
40Decnumber = r'[1-9]\d*[lL]?'
Guido van Rossum1aec3231997-04-08 14:24:39 +000041Intnumber = group(Hexnumber, Octnumber, Decnumber)
Guido van Rossum3b631771997-10-27 20:44:15 +000042Exponent = r'[eE][-+]?\d+'
43Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent)
44Expfloat = r'[1-9]\d*' + Exponent
Guido van Rossum1aec3231997-04-08 14:24:39 +000045Floatnumber = group(Pointfloat, Expfloat)
Guido van Rossum3b631771997-10-27 20:44:15 +000046Imagnumber = group(r'0[jJ]', r'[1-9]\d*[jJ]', Floatnumber + r'[jJ]')
Guido van Rossum1aec3231997-04-08 14:24:39 +000047Number = group(Imagnumber, Floatnumber, Intnumber)
Guido van Rossum4d8e8591992-01-01 19:34:47 +000048
Tim Petersde495832000-10-07 05:09:39 +000049# Tail end of ' string.
50Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
51# Tail end of " string.
52Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
53# Tail end of ''' string.
54Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
55# Tail end of """ string.
56Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
Guido van Rossumfefc9221997-10-27 21:17:24 +000057Triple = group("[rR]?'''", '[rR]?"""')
Tim Petersde495832000-10-07 05:09:39 +000058# Single-line ' or " string.
59String = group(r"[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
60 r'[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
Guido van Rossum4d8e8591992-01-01 19:34:47 +000061
Tim Petersde495832000-10-07 05:09:39 +000062# Because of leftmost-then-longest match semantics, be sure to put the
63# longest operators first (e.g., if = came before ==, == would get
64# recognized as two instances of =).
65Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=",
66 r"[+\-*/%&|^=<>]=?",
67 r"~")
Thomas Wouterse1519a12000-08-24 21:44:52 +000068
Guido van Rossum4d8e8591992-01-01 19:34:47 +000069Bracket = '[][(){}]'
Guido van Rossum3b631771997-10-27 20:44:15 +000070Special = group(r'\r?\n', r'[:;.,`]')
Guido van Rossumfc6f5331997-03-07 00:21:12 +000071Funny = group(Operator, Bracket, Special)
Guido van Rossum4d8e8591992-01-01 19:34:47 +000072
Guido van Rossum3b631771997-10-27 20:44:15 +000073PlainToken = group(Number, Funny, String, Name)
Guido van Rossumfc6f5331997-03-07 00:21:12 +000074Token = Ignore + PlainToken
Guido van Rossum4d8e8591992-01-01 19:34:47 +000075
Tim Petersde495832000-10-07 05:09:39 +000076# First (or only) line of ' or " string.
77ContStr = group(r"[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" + group("'", r'\\\r?\n'),
78 r'[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' + group('"', r'\\\r?\n'))
Guido van Rossum3b631771997-10-27 20:44:15 +000079PseudoExtras = group(r'\\\r?\n', Comment, Triple)
80PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
Guido van Rossum1aec3231997-04-08 14:24:39 +000081
Guido van Rossum3b631771997-10-27 20:44:15 +000082tokenprog, pseudoprog, single3prog, double3prog = map(
83 re.compile, (Token, PseudoToken, Single3, Double3))
Guido van Rossumfefc9221997-10-27 21:17:24 +000084endprogs = {"'": re.compile(Single), '"': re.compile(Double),
Guido van Rossum3b631771997-10-27 20:44:15 +000085 "'''": single3prog, '"""': double3prog,
Guido van Rossumfefc9221997-10-27 21:17:24 +000086 "r'''": single3prog, 'r"""': double3prog,
87 "R'''": single3prog, 'R"""': double3prog, 'r': None, 'R': None}
Guido van Rossum4d8e8591992-01-01 19:34:47 +000088
Guido van Rossumfc6f5331997-03-07 00:21:12 +000089tabsize = 8
Fred Drake9b8d8012000-08-17 04:45:13 +000090
91class TokenError(Exception):
92 pass
93
Guido van Rossum1aec3231997-04-08 14:24:39 +000094def printtoken(type, token, (srow, scol), (erow, ecol), line): # for testing
95 print "%d,%d-%d,%d:\t%s\t%s" % \
96 (srow, scol, erow, ecol, tok_name[type], repr(token))
Guido van Rossum4d8e8591992-01-01 19:34:47 +000097
Guido van Rossum1aec3231997-04-08 14:24:39 +000098def tokenize(readline, tokeneater=printtoken):
99 lnum = parenlev = continued = 0
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000100 namechars, numchars = string.letters + '_', string.digits
Guido van Rossumde655271997-04-09 17:15:54 +0000101 contstr, needcont = '', 0
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000102 contline = None
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000103 indents = [0]
Guido van Rossum1aec3231997-04-08 14:24:39 +0000104
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000105 while 1: # loop over lines in stream
106 line = readline()
Guido van Rossum1aec3231997-04-08 14:24:39 +0000107 lnum = lnum + 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000108 pos, max = 0, len(line)
109
110 if contstr: # continued string
Guido van Rossumde655271997-04-09 17:15:54 +0000111 if not line:
112 raise TokenError, ("EOF in multi-line string", strstart)
Guido van Rossum3b631771997-10-27 20:44:15 +0000113 endmatch = endprog.match(line)
114 if endmatch:
115 pos = end = endmatch.end(0)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000116 tokeneater(STRING, contstr + line[:end],
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000117 strstart, (lnum, end), contline + line)
Guido van Rossumde655271997-04-09 17:15:54 +0000118 contstr, needcont = '', 0
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000119 contline = None
Guido van Rossumde655271997-04-09 17:15:54 +0000120 elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
121 tokeneater(ERRORTOKEN, contstr + line,
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000122 strstart, (lnum, len(line)), contline)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000123 contstr = ''
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000124 contline = None
Guido van Rossumde655271997-04-09 17:15:54 +0000125 continue
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000126 else:
127 contstr = contstr + line
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000128 contline = contline + line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000129 continue
130
Guido van Rossum1aec3231997-04-08 14:24:39 +0000131 elif parenlev == 0 and not continued: # new statement
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000132 if not line: break
133 column = 0
Guido van Rossum1aec3231997-04-08 14:24:39 +0000134 while pos < max: # measure leading whitespace
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000135 if line[pos] == ' ': column = column + 1
Guido van Rossum1aec3231997-04-08 14:24:39 +0000136 elif line[pos] == '\t': column = (column/tabsize + 1)*tabsize
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000137 elif line[pos] == '\f': column = 0
138 else: break
139 pos = pos + 1
Guido van Rossumde655271997-04-09 17:15:54 +0000140 if pos == max: break
Guido van Rossum1aec3231997-04-08 14:24:39 +0000141
142 if line[pos] in '#\r\n': # skip comments or blank lines
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000143 tokeneater((NL, COMMENT)[line[pos] == '#'], line[pos:],
Guido van Rossum1aec3231997-04-08 14:24:39 +0000144 (lnum, pos), (lnum, len(line)), line)
145 continue
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000146
147 if column > indents[-1]: # count indents or dedents
148 indents.append(column)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000149 tokeneater(INDENT, line[:pos], (lnum, 0), (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000150 while column < indents[-1]:
151 indents = indents[:-1]
Guido van Rossumde655271997-04-09 17:15:54 +0000152 tokeneater(DEDENT, '', (lnum, pos), (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000153
154 else: # continued statement
Guido van Rossumde655271997-04-09 17:15:54 +0000155 if not line:
156 raise TokenError, ("EOF in multi-line statement", (lnum, 0))
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000157 continued = 0
158
159 while pos < max:
Guido van Rossum3b631771997-10-27 20:44:15 +0000160 pseudomatch = pseudoprog.match(line, pos)
161 if pseudomatch: # scan for tokens
162 start, end = pseudomatch.span(1)
Guido van Rossumde655271997-04-09 17:15:54 +0000163 spos, epos, pos = (lnum, start), (lnum, end), end
Guido van Rossum1aec3231997-04-08 14:24:39 +0000164 token, initial = line[start:end], line[start]
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000165
Guido van Rossum3b631771997-10-27 20:44:15 +0000166 if initial in numchars \
Guido van Rossumde655271997-04-09 17:15:54 +0000167 or (initial == '.' and token != '.'): # ordinary number
Guido van Rossum1aec3231997-04-08 14:24:39 +0000168 tokeneater(NUMBER, token, spos, epos, line)
169 elif initial in '\r\n':
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000170 tokeneater(parenlev > 0 and NL or NEWLINE,
171 token, spos, epos, line)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000172 elif initial == '#':
173 tokeneater(COMMENT, token, spos, epos, line)
Guido van Rossumfefc9221997-10-27 21:17:24 +0000174 elif token in ("'''", '"""', # triple-quoted
175 "r'''", 'r"""', "R'''", 'R"""'):
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000176 endprog = endprogs[token]
Guido van Rossum3b631771997-10-27 20:44:15 +0000177 endmatch = endprog.match(line, pos)
178 if endmatch: # all on one line
179 pos = endmatch.end(0)
Guido van Rossum1aec3231997-04-08 14:24:39 +0000180 token = line[start:pos]
181 tokeneater(STRING, token, spos, (lnum, pos), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000182 else:
Guido van Rossum1aec3231997-04-08 14:24:39 +0000183 strstart = (lnum, start) # multiple lines
184 contstr = line[start:]
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000185 contline = line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000186 break
Guido van Rossumfefc9221997-10-27 21:17:24 +0000187 elif initial in ("'", '"') or \
188 token[:2] in ("r'", 'r"', "R'", 'R"'):
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000189 if token[-1] == '\n': # continued string
Guido van Rossum1aec3231997-04-08 14:24:39 +0000190 strstart = (lnum, start)
Guido van Rossum3b631771997-10-27 20:44:15 +0000191 endprog = endprogs[initial] or endprogs[token[1]]
Guido van Rossumde655271997-04-09 17:15:54 +0000192 contstr, needcont = line[start:], 1
Guido van Rossuma90c78b1998-04-03 16:05:38 +0000193 contline = line
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000194 break
195 else: # ordinary string
Guido van Rossum1aec3231997-04-08 14:24:39 +0000196 tokeneater(STRING, token, spos, epos, line)
Guido van Rossum3b631771997-10-27 20:44:15 +0000197 elif initial in namechars: # ordinary name
198 tokeneater(NAME, token, spos, epos, line)
199 elif initial == '\\': # continued stmt
200 continued = 1
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000201 else:
Guido van Rossum1aec3231997-04-08 14:24:39 +0000202 if initial in '([{': parenlev = parenlev + 1
203 elif initial in ')]}': parenlev = parenlev - 1
204 tokeneater(OP, token, spos, epos, line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000205 else:
Guido van Rossumde655271997-04-09 17:15:54 +0000206 tokeneater(ERRORTOKEN, line[pos],
207 (lnum, pos), (lnum, pos+1), line)
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000208 pos = pos + 1
209
210 for indent in indents[1:]: # pop remaining indent levels
Guido van Rossum1aec3231997-04-08 14:24:39 +0000211 tokeneater(DEDENT, '', (lnum, 0), (lnum, 0), '')
Guido van Rossumde655271997-04-09 17:15:54 +0000212 tokeneater(ENDMARKER, '', (lnum, 0), (lnum, 0), '')
Guido van Rossumfc6f5331997-03-07 00:21:12 +0000213
214if __name__ == '__main__': # testing
215 import sys
Guido van Rossumde655271997-04-09 17:15:54 +0000216 if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline)
Guido van Rossum2b1566b1997-06-03 22:05:15 +0000217 else: tokenize(sys.stdin.readline)
Guido van Rossum3b631771997-10-27 20:44:15 +0000218