Guido van Rossum | b51eaa1 | 1997-03-07 00:21:55 +0000 | [diff] [blame] | 1 | """Tokenization help for Python programs. |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 2 | |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 3 | generate_tokens(readline) is a generator that breaks a stream of |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 4 | text into Python tokens. It accepts a readline-like method which is called |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 5 | repeatedly to get the next line of input (or "" for EOF). It generates |
| 6 | 5-tuples with these members: |
| 7 | |
| 8 | the token type (see token.py) |
| 9 | the token (a string) |
| 10 | the starting (row, column) indices of the token (a 2-tuple of ints) |
| 11 | the ending (row, column) indices of the token (a 2-tuple of ints) |
| 12 | the original line (string) |
| 13 | |
| 14 | It is designed to match the working of the Python tokenizer exactly, except |
| 15 | that it produces COMMENT tokens for comments and gives type OP for all |
| 16 | operators |
| 17 | |
| 18 | Older entry points |
| 19 | tokenize_loop(readline, tokeneater) |
| 20 | tokenize(readline, tokeneater=printtoken) |
| 21 | are the same, except instead of generating tokens, tokeneater is a callback |
| 22 | function to which the 5 fields described above are passed as 5 arguments, |
| 23 | each time a new token is found.""" |
Guido van Rossum | b51eaa1 | 1997-03-07 00:21:55 +0000 | [diff] [blame] | 24 | |
Ka-Ping Yee | 244c593 | 2001-03-01 13:56:40 +0000 | [diff] [blame] | 25 | __author__ = 'Ka-Ping Yee <ping@lfw.org>' |
Ka-Ping Yee | 4f64c13 | 2001-03-01 17:11:17 +0000 | [diff] [blame] | 26 | __credits__ = \ |
Raymond Hettinger | 8a7e76b | 2006-12-02 02:00:39 +0000 | [diff] [blame] | 27 | 'GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, Skip Montanaro, Raymond Hettinger' |
Guido van Rossum | b51eaa1 | 1997-03-07 00:21:55 +0000 | [diff] [blame] | 28 | |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 29 | import string, re |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 30 | from token import * |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 31 | |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 32 | import token |
Raymond Hettinger | 78a7aee | 2002-11-05 06:06:02 +0000 | [diff] [blame] | 33 | __all__ = [x for x in dir(token) if x[0] != '_'] + ["COMMENT", "tokenize", |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 34 | "generate_tokens", "NL", "untokenize"] |
Neal Norwitz | e98d16e | 2002-03-26 16:20:26 +0000 | [diff] [blame] | 35 | del x |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 36 | del token |
| 37 | |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 38 | COMMENT = N_TOKENS |
| 39 | tok_name[COMMENT] = 'COMMENT' |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 40 | NL = N_TOKENS + 1 |
| 41 | tok_name[NL] = 'NL' |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 42 | N_TOKENS += 2 |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 43 | |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 44 | def group(*choices): return '(' + '|'.join(choices) + ')' |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 45 | def any(*choices): return group(*choices) + '*' |
| 46 | def maybe(*choices): return group(*choices) + '?' |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 47 | |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 48 | Whitespace = r'[ \f\t]*' |
| 49 | Comment = r'#[^\r\n]*' |
| 50 | Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment) |
| 51 | Name = r'[a-zA-Z_]\w*' |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 52 | |
Georg Brandl | 14404b6 | 2008-01-19 19:27:05 +0000 | [diff] [blame] | 53 | Hexnumber = r'0[xX][\da-fA-F]+[lL]?' |
Eric Smith | 0aed07a | 2008-03-17 19:43:40 +0000 | [diff] [blame] | 54 | Octnumber = r'(0[oO][0-7]+)|(0[0-7]*)[lL]?' |
| 55 | Binnumber = r'0[bB][01]+[lL]?' |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 56 | Decnumber = r'[1-9]\d*[lL]?' |
Eric Smith | 0aed07a | 2008-03-17 19:43:40 +0000 | [diff] [blame] | 57 | Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber) |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 58 | Exponent = r'[eE][-+]?\d+' |
| 59 | Pointfloat = group(r'\d+\.\d*', r'\.\d+') + maybe(Exponent) |
Tim Peters | d507dab | 2001-08-30 20:51:59 +0000 | [diff] [blame] | 60 | Expfloat = r'\d+' + Exponent |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 61 | Floatnumber = group(Pointfloat, Expfloat) |
Tim Peters | d507dab | 2001-08-30 20:51:59 +0000 | [diff] [blame] | 62 | Imagnumber = group(r'\d+[jJ]', Floatnumber + r'[jJ]') |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 63 | Number = group(Imagnumber, Floatnumber, Intnumber) |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 64 | |
Tim Peters | de49583 | 2000-10-07 05:09:39 +0000 | [diff] [blame] | 65 | # Tail end of ' string. |
| 66 | Single = r"[^'\\]*(?:\\.[^'\\]*)*'" |
| 67 | # Tail end of " string. |
| 68 | Double = r'[^"\\]*(?:\\.[^"\\]*)*"' |
| 69 | # Tail end of ''' string. |
| 70 | Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''" |
| 71 | # Tail end of """ string. |
| 72 | Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""' |
Ka-Ping Yee | 1ff08b1 | 2001-01-15 22:04:30 +0000 | [diff] [blame] | 73 | Triple = group("[uU]?[rR]?'''", '[uU]?[rR]?"""') |
Tim Peters | de49583 | 2000-10-07 05:09:39 +0000 | [diff] [blame] | 74 | # Single-line ' or " string. |
Ka-Ping Yee | 1ff08b1 | 2001-01-15 22:04:30 +0000 | [diff] [blame] | 75 | String = group(r"[uU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*'", |
| 76 | r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*"') |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 77 | |
Tim Peters | de49583 | 2000-10-07 05:09:39 +0000 | [diff] [blame] | 78 | # Because of leftmost-then-longest match semantics, be sure to put the |
| 79 | # longest operators first (e.g., if = came before ==, == would get |
| 80 | # recognized as two instances of =). |
| 81 | Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=", |
Guido van Rossum | 96204f5 | 2001-08-08 05:04:07 +0000 | [diff] [blame] | 82 | r"//=?", |
Tim Peters | de49583 | 2000-10-07 05:09:39 +0000 | [diff] [blame] | 83 | r"[+\-*/%&|^=<>]=?", |
| 84 | r"~") |
Thomas Wouters | e1519a1 | 2000-08-24 21:44:52 +0000 | [diff] [blame] | 85 | |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 86 | Bracket = '[][(){}]' |
Anthony Baxter | c2a5a63 | 2004-08-02 06:10:11 +0000 | [diff] [blame] | 87 | Special = group(r'\r?\n', r'[:;.,`@]') |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 88 | Funny = group(Operator, Bracket, Special) |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 89 | |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 90 | PlainToken = group(Number, Funny, String, Name) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 91 | Token = Ignore + PlainToken |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 92 | |
Tim Peters | de49583 | 2000-10-07 05:09:39 +0000 | [diff] [blame] | 93 | # First (or only) line of ' or " string. |
Ka-Ping Yee | 1ff08b1 | 2001-01-15 22:04:30 +0000 | [diff] [blame] | 94 | ContStr = group(r"[uU]?[rR]?'[^\n'\\]*(?:\\.[^\n'\\]*)*" + |
| 95 | group("'", r'\\\r?\n'), |
| 96 | r'[uU]?[rR]?"[^\n"\\]*(?:\\.[^\n"\\]*)*' + |
| 97 | group('"', r'\\\r?\n')) |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 98 | PseudoExtras = group(r'\\\r?\n', Comment, Triple) |
| 99 | PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name) |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 100 | |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 101 | tokenprog, pseudoprog, single3prog, double3prog = map( |
| 102 | re.compile, (Token, PseudoToken, Single3, Double3)) |
Guido van Rossum | fefc922 | 1997-10-27 21:17:24 +0000 | [diff] [blame] | 103 | endprogs = {"'": re.compile(Single), '"': re.compile(Double), |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 104 | "'''": single3prog, '"""': double3prog, |
Guido van Rossum | fefc922 | 1997-10-27 21:17:24 +0000 | [diff] [blame] | 105 | "r'''": single3prog, 'r"""': double3prog, |
Ka-Ping Yee | 1ff08b1 | 2001-01-15 22:04:30 +0000 | [diff] [blame] | 106 | "u'''": single3prog, 'u"""': double3prog, |
| 107 | "ur'''": single3prog, 'ur"""': double3prog, |
| 108 | "R'''": single3prog, 'R"""': double3prog, |
| 109 | "U'''": single3prog, 'U"""': double3prog, |
| 110 | "uR'''": single3prog, 'uR"""': double3prog, |
| 111 | "Ur'''": single3prog, 'Ur"""': double3prog, |
| 112 | "UR'''": single3prog, 'UR"""': double3prog, |
Christian Heimes | 288e89a | 2008-01-18 18:24:07 +0000 | [diff] [blame] | 113 | "b'''": single3prog, 'b"""': double3prog, |
| 114 | "br'''": single3prog, 'br"""': double3prog, |
| 115 | "B'''": single3prog, 'B"""': double3prog, |
| 116 | "bR'''": single3prog, 'bR"""': double3prog, |
| 117 | "Br'''": single3prog, 'Br"""': double3prog, |
| 118 | "BR'''": single3prog, 'BR"""': double3prog, |
| 119 | 'r': None, 'R': None, 'u': None, 'U': None, |
| 120 | 'b': None, 'B': None} |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 121 | |
Guido van Rossum | 9d6897a | 2002-08-24 06:54:19 +0000 | [diff] [blame] | 122 | triple_quoted = {} |
| 123 | for t in ("'''", '"""', |
| 124 | "r'''", 'r"""', "R'''", 'R"""', |
| 125 | "u'''", 'u"""', "U'''", 'U"""', |
| 126 | "ur'''", 'ur"""', "Ur'''", 'Ur"""', |
Christian Heimes | 288e89a | 2008-01-18 18:24:07 +0000 | [diff] [blame] | 127 | "uR'''", 'uR"""', "UR'''", 'UR"""', |
| 128 | "b'''", 'b"""', "B'''", 'B"""', |
| 129 | "br'''", 'br"""', "Br'''", 'Br"""', |
| 130 | "bR'''", 'bR"""', "BR'''", 'BR"""'): |
Guido van Rossum | 9d6897a | 2002-08-24 06:54:19 +0000 | [diff] [blame] | 131 | triple_quoted[t] = t |
| 132 | single_quoted = {} |
| 133 | for t in ("'", '"', |
| 134 | "r'", 'r"', "R'", 'R"', |
| 135 | "u'", 'u"', "U'", 'U"', |
| 136 | "ur'", 'ur"', "Ur'", 'Ur"', |
Christian Heimes | 288e89a | 2008-01-18 18:24:07 +0000 | [diff] [blame] | 137 | "uR'", 'uR"', "UR'", 'UR"', |
| 138 | "b'", 'b"', "B'", 'B"', |
| 139 | "br'", 'br"', "Br'", 'Br"', |
| 140 | "bR'", 'bR"', "BR'", 'BR"' ): |
Guido van Rossum | 9d6897a | 2002-08-24 06:54:19 +0000 | [diff] [blame] | 141 | single_quoted[t] = t |
| 142 | |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 143 | tabsize = 8 |
Fred Drake | 9b8d801 | 2000-08-17 04:45:13 +0000 | [diff] [blame] | 144 | |
Ka-Ping Yee | 28c62bb | 2001-03-23 05:22:49 +0000 | [diff] [blame] | 145 | class TokenError(Exception): pass |
| 146 | |
| 147 | class StopTokenizing(Exception): pass |
Fred Drake | 9b8d801 | 2000-08-17 04:45:13 +0000 | [diff] [blame] | 148 | |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 149 | def printtoken(type, token, (srow, scol), (erow, ecol), line): # for testing |
| 150 | print "%d,%d-%d,%d:\t%s\t%s" % \ |
| 151 | (srow, scol, erow, ecol, tok_name[type], repr(token)) |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 152 | |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 153 | def tokenize(readline, tokeneater=printtoken): |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 154 | """ |
| 155 | The tokenize() function accepts two parameters: one representing the |
| 156 | input stream, and one providing an output mechanism for tokenize(). |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 157 | |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 158 | The first parameter, readline, must be a callable object which provides |
| 159 | the same interface as the readline() method of built-in file objects. |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 160 | Each call to the function should return one line of input as a string. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 161 | |
| 162 | The second parameter, tokeneater, must also be a callable object. It is |
| 163 | called once for each token, with five arguments, corresponding to the |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 164 | tuples generated by generate_tokens(). |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 165 | """ |
Ka-Ping Yee | 28c62bb | 2001-03-23 05:22:49 +0000 | [diff] [blame] | 166 | try: |
| 167 | tokenize_loop(readline, tokeneater) |
| 168 | except StopTokenizing: |
| 169 | pass |
| 170 | |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 171 | # backwards compatible interface |
Ka-Ping Yee | 28c62bb | 2001-03-23 05:22:49 +0000 | [diff] [blame] | 172 | def tokenize_loop(readline, tokeneater): |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 173 | for token_info in generate_tokens(readline): |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 174 | tokeneater(*token_info) |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 175 | |
Jeremy Hylton | 76467ba | 2006-08-23 21:14:03 +0000 | [diff] [blame] | 176 | class Untokenizer: |
| 177 | |
| 178 | def __init__(self): |
| 179 | self.tokens = [] |
| 180 | self.prev_row = 1 |
| 181 | self.prev_col = 0 |
| 182 | |
| 183 | def add_whitespace(self, start): |
| 184 | row, col = start |
Jeremy Hylton | 39c532c | 2006-08-23 21:26:46 +0000 | [diff] [blame] | 185 | assert row <= self.prev_row |
Jeremy Hylton | 76467ba | 2006-08-23 21:14:03 +0000 | [diff] [blame] | 186 | col_offset = col - self.prev_col |
| 187 | if col_offset: |
| 188 | self.tokens.append(" " * col_offset) |
| 189 | |
| 190 | def untokenize(self, iterable): |
| 191 | for t in iterable: |
| 192 | if len(t) == 2: |
| 193 | self.compat(t, iterable) |
| 194 | break |
| 195 | tok_type, token, start, end, line = t |
| 196 | self.add_whitespace(start) |
| 197 | self.tokens.append(token) |
| 198 | self.prev_row, self.prev_col = end |
| 199 | if tok_type in (NEWLINE, NL): |
| 200 | self.prev_row += 1 |
| 201 | self.prev_col = 0 |
| 202 | return "".join(self.tokens) |
| 203 | |
| 204 | def compat(self, token, iterable): |
| 205 | startline = False |
| 206 | indents = [] |
| 207 | toks_append = self.tokens.append |
| 208 | toknum, tokval = token |
| 209 | if toknum in (NAME, NUMBER): |
| 210 | tokval += ' ' |
| 211 | if toknum in (NEWLINE, NL): |
| 212 | startline = True |
| 213 | for tok in iterable: |
| 214 | toknum, tokval = tok[:2] |
| 215 | |
| 216 | if toknum in (NAME, NUMBER): |
| 217 | tokval += ' ' |
| 218 | |
| 219 | if toknum == INDENT: |
| 220 | indents.append(tokval) |
| 221 | continue |
| 222 | elif toknum == DEDENT: |
| 223 | indents.pop() |
| 224 | continue |
| 225 | elif toknum in (NEWLINE, NL): |
| 226 | startline = True |
| 227 | elif startline and indents: |
| 228 | toks_append(indents[-1]) |
| 229 | startline = False |
| 230 | toks_append(tokval) |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 231 | |
| 232 | def untokenize(iterable): |
| 233 | """Transform tokens back into Python source code. |
| 234 | |
| 235 | Each element returned by the iterable must be a token sequence |
Jeremy Hylton | 76467ba | 2006-08-23 21:14:03 +0000 | [diff] [blame] | 236 | with at least two elements, a token number and token value. If |
| 237 | only two tokens are passed, the resulting output is poor. |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 238 | |
Jeremy Hylton | 76467ba | 2006-08-23 21:14:03 +0000 | [diff] [blame] | 239 | Round-trip invariant for full input: |
| 240 | Untokenized source will match input source exactly |
| 241 | |
| 242 | Round-trip invariant for limited intput: |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 243 | # Output text will tokenize the back to the input |
| 244 | t1 = [tok[:2] for tok in generate_tokens(f.readline)] |
| 245 | newcode = untokenize(t1) |
| 246 | readline = iter(newcode.splitlines(1)).next |
| 247 | t2 = [tok[:2] for tokin generate_tokens(readline)] |
| 248 | assert t1 == t2 |
| 249 | """ |
Jeremy Hylton | 76467ba | 2006-08-23 21:14:03 +0000 | [diff] [blame] | 250 | ut = Untokenizer() |
| 251 | return ut.untokenize(iterable) |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 252 | |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 253 | def generate_tokens(readline): |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 254 | """ |
| 255 | The generate_tokens() generator requires one argment, readline, which |
| 256 | must be a callable object which provides the same interface as the |
| 257 | readline() method of built-in file objects. Each call to the function |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 258 | should return one line of input as a string. Alternately, readline |
| 259 | can be a callable function terminating with StopIteration: |
| 260 | readline = open(myfile).next # Example of alternate readline |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 261 | |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 262 | The generator produces 5-tuples with these members: the token type; the |
| 263 | token string; a 2-tuple (srow, scol) of ints specifying the row and |
| 264 | column where the token begins in the source; a 2-tuple (erow, ecol) of |
| 265 | ints specifying the row and column where the token ends in the source; |
| 266 | and the line on which the token was found. The line passed is the |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 267 | logical line; continuation lines are included. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 268 | """ |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 269 | lnum = parenlev = continued = 0 |
Fred Drake | 79e75e1 | 2001-07-20 19:05:50 +0000 | [diff] [blame] | 270 | namechars, numchars = string.ascii_letters + '_', '0123456789' |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 271 | contstr, needcont = '', 0 |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 272 | contline = None |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 273 | indents = [0] |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 274 | |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 275 | while 1: # loop over lines in stream |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 276 | try: |
| 277 | line = readline() |
| 278 | except StopIteration: |
| 279 | line = '' |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 280 | lnum = lnum + 1 |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 281 | pos, max = 0, len(line) |
| 282 | |
| 283 | if contstr: # continued string |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 284 | if not line: |
| 285 | raise TokenError, ("EOF in multi-line string", strstart) |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 286 | endmatch = endprog.match(line) |
| 287 | if endmatch: |
| 288 | pos = end = endmatch.end(0) |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 289 | yield (STRING, contstr + line[:end], |
Jeremy Hylton | 76467ba | 2006-08-23 21:14:03 +0000 | [diff] [blame] | 290 | strstart, (lnum, end), contline + line) |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 291 | contstr, needcont = '', 0 |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 292 | contline = None |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 293 | elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n': |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 294 | yield (ERRORTOKEN, contstr + line, |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 295 | strstart, (lnum, len(line)), contline) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 296 | contstr = '' |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 297 | contline = None |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 298 | continue |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 299 | else: |
| 300 | contstr = contstr + line |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 301 | contline = contline + line |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 302 | continue |
| 303 | |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 304 | elif parenlev == 0 and not continued: # new statement |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 305 | if not line: break |
| 306 | column = 0 |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 307 | while pos < max: # measure leading whitespace |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 308 | if line[pos] == ' ': column = column + 1 |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 309 | elif line[pos] == '\t': column = (column/tabsize + 1)*tabsize |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 310 | elif line[pos] == '\f': column = 0 |
| 311 | else: break |
| 312 | pos = pos + 1 |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 313 | if pos == max: break |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 314 | |
| 315 | if line[pos] in '#\r\n': # skip comments or blank lines |
Jeremy Hylton | 76467ba | 2006-08-23 21:14:03 +0000 | [diff] [blame] | 316 | if line[pos] == '#': |
| 317 | comment_token = line[pos:].rstrip('\r\n') |
| 318 | nl_pos = pos + len(comment_token) |
| 319 | yield (COMMENT, comment_token, |
| 320 | (lnum, pos), (lnum, pos + len(comment_token)), line) |
| 321 | yield (NL, line[nl_pos:], |
| 322 | (lnum, nl_pos), (lnum, len(line)), line) |
| 323 | else: |
| 324 | yield ((NL, COMMENT)[line[pos] == '#'], line[pos:], |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 325 | (lnum, pos), (lnum, len(line)), line) |
| 326 | continue |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 327 | |
| 328 | if column > indents[-1]: # count indents or dedents |
| 329 | indents.append(column) |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 330 | yield (INDENT, line[:pos], (lnum, 0), (lnum, pos), line) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 331 | while column < indents[-1]: |
Raymond Hettinger | da99d1c | 2005-06-21 07:43:58 +0000 | [diff] [blame] | 332 | if column not in indents: |
| 333 | raise IndentationError( |
Georg Brandl | 2463f8f | 2006-08-14 21:34:08 +0000 | [diff] [blame] | 334 | "unindent does not match any outer indentation level", |
| 335 | ("<tokenize>", lnum, pos, line)) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 336 | indents = indents[:-1] |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 337 | yield (DEDENT, '', (lnum, pos), (lnum, pos), line) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 338 | |
| 339 | else: # continued statement |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 340 | if not line: |
| 341 | raise TokenError, ("EOF in multi-line statement", (lnum, 0)) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 342 | continued = 0 |
| 343 | |
| 344 | while pos < max: |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 345 | pseudomatch = pseudoprog.match(line, pos) |
| 346 | if pseudomatch: # scan for tokens |
| 347 | start, end = pseudomatch.span(1) |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 348 | spos, epos, pos = (lnum, start), (lnum, end), end |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 349 | token, initial = line[start:end], line[start] |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 350 | |
Ka-Ping Yee | 28c62bb | 2001-03-23 05:22:49 +0000 | [diff] [blame] | 351 | if initial in numchars or \ |
| 352 | (initial == '.' and token != '.'): # ordinary number |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 353 | yield (NUMBER, token, spos, epos, line) |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 354 | elif initial in '\r\n': |
Jeremy Hylton | 76467ba | 2006-08-23 21:14:03 +0000 | [diff] [blame] | 355 | yield (NL if parenlev > 0 else NEWLINE, |
| 356 | token, spos, epos, line) |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 357 | elif initial == '#': |
Jeremy Hylton | 76467ba | 2006-08-23 21:14:03 +0000 | [diff] [blame] | 358 | assert not token.endswith("\n") |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 359 | yield (COMMENT, token, spos, epos, line) |
Guido van Rossum | 9d6897a | 2002-08-24 06:54:19 +0000 | [diff] [blame] | 360 | elif token in triple_quoted: |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 361 | endprog = endprogs[token] |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 362 | endmatch = endprog.match(line, pos) |
| 363 | if endmatch: # all on one line |
| 364 | pos = endmatch.end(0) |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 365 | token = line[start:pos] |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 366 | yield (STRING, token, spos, (lnum, pos), line) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 367 | else: |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 368 | strstart = (lnum, start) # multiple lines |
| 369 | contstr = line[start:] |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 370 | contline = line |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 371 | break |
Guido van Rossum | 9d6897a | 2002-08-24 06:54:19 +0000 | [diff] [blame] | 372 | elif initial in single_quoted or \ |
| 373 | token[:2] in single_quoted or \ |
| 374 | token[:3] in single_quoted: |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 375 | if token[-1] == '\n': # continued string |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 376 | strstart = (lnum, start) |
Ka-Ping Yee | 1ff08b1 | 2001-01-15 22:04:30 +0000 | [diff] [blame] | 377 | endprog = (endprogs[initial] or endprogs[token[1]] or |
| 378 | endprogs[token[2]]) |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 379 | contstr, needcont = line[start:], 1 |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 380 | contline = line |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 381 | break |
| 382 | else: # ordinary string |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 383 | yield (STRING, token, spos, epos, line) |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 384 | elif initial in namechars: # ordinary name |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 385 | yield (NAME, token, spos, epos, line) |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 386 | elif initial == '\\': # continued stmt |
| 387 | continued = 1 |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 388 | else: |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 389 | if initial in '([{': parenlev = parenlev + 1 |
| 390 | elif initial in ')]}': parenlev = parenlev - 1 |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 391 | yield (OP, token, spos, epos, line) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 392 | else: |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 393 | yield (ERRORTOKEN, line[pos], |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 394 | (lnum, pos), (lnum, pos+1), line) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 395 | pos = pos + 1 |
| 396 | |
| 397 | for indent in indents[1:]: # pop remaining indent levels |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 398 | yield (DEDENT, '', (lnum, 0), (lnum, 0), '') |
| 399 | yield (ENDMARKER, '', (lnum, 0), (lnum, 0), '') |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 400 | |
| 401 | if __name__ == '__main__': # testing |
| 402 | import sys |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 403 | if len(sys.argv) > 1: tokenize(open(sys.argv[1]).readline) |
Guido van Rossum | 2b1566b | 1997-06-03 22:05:15 +0000 | [diff] [blame] | 404 | else: tokenize(sys.stdin.readline) |