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 | |
Florent Xicluna | 43e4ea1 | 2010-09-03 19:54:02 +0000 | [diff] [blame] | 3 | tokenize(readline) is a generator that breaks a stream of bytes into |
| 4 | Python tokens. It decodes the bytes according to PEP-0263 for |
| 5 | determining source file encoding. |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 6 | |
Florent Xicluna | 43e4ea1 | 2010-09-03 19:54:02 +0000 | [diff] [blame] | 7 | It accepts a readline-like method which is called repeatedly to get the |
| 8 | next line of input (or b"" for EOF). It generates 5-tuples with these |
| 9 | members: |
Tim Peters | 4efb6e9 | 2001-06-29 23:51:08 +0000 | [diff] [blame] | 10 | |
| 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 | |
| 17 | It is designed to match the working of the Python tokenizer exactly, except |
| 18 | that it produces COMMENT tokens for comments and gives type OP for all |
Florent Xicluna | 43e4ea1 | 2010-09-03 19:54:02 +0000 | [diff] [blame] | 19 | operators. Additionally, all token lists start with an ENCODING token |
| 20 | which tells you which encoding was used to decode the bytes stream. |
| 21 | """ |
Guido van Rossum | b51eaa1 | 1997-03-07 00:21:55 +0000 | [diff] [blame] | 22 | |
Ka-Ping Yee | 244c593 | 2001-03-01 13:56:40 +0000 | [diff] [blame] | 23 | __author__ = 'Ka-Ping Yee <ping@lfw.org>' |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 24 | __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, ' |
| 25 | 'Skip Montanaro, Raymond Hettinger, Trent Nelson, ' |
| 26 | 'Michael Foord') |
Serhiy Storchaka | cf4a2f2 | 2015-03-11 17:18:03 +0200 | [diff] [blame] | 27 | from builtins import open as _builtin_open |
Benjamin Peterson | 433f32c | 2008-12-12 01:25:05 +0000 | [diff] [blame] | 28 | from codecs import lookup, BOM_UTF8 |
Raymond Hettinger | 3fb79c7 | 2010-09-09 07:15:18 +0000 | [diff] [blame] | 29 | import collections |
Victor Stinner | 58c0752 | 2010-11-09 01:08:59 +0000 | [diff] [blame] | 30 | from io import TextIOWrapper |
Terry Jan Reedy | 5b8d2c3 | 2014-02-17 23:12:16 -0500 | [diff] [blame] | 31 | from itertools import chain |
| 32 | import re |
| 33 | import sys |
| 34 | from token import * |
| 35 | |
Serhiy Storchaka | dafea85 | 2013-09-16 23:51:56 +0300 | [diff] [blame] | 36 | cookie_re = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)', re.ASCII) |
Serhiy Storchaka | 768c16c | 2014-01-09 18:36:09 +0200 | [diff] [blame] | 37 | blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII) |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 38 | |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 39 | import token |
Alexander Belopolsky | b9d10d0 | 2010-11-11 14:07:41 +0000 | [diff] [blame] | 40 | __all__ = token.__all__ + ["COMMENT", "tokenize", "detect_encoding", |
| 41 | "NL", "untokenize", "ENCODING", "TokenInfo"] |
Skip Montanaro | 40fc160 | 2001-03-01 04:27:19 +0000 | [diff] [blame] | 42 | del token |
| 43 | |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 44 | COMMENT = N_TOKENS |
| 45 | tok_name[COMMENT] = 'COMMENT' |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 46 | NL = N_TOKENS + 1 |
| 47 | tok_name[NL] = 'NL' |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 48 | ENCODING = N_TOKENS + 2 |
| 49 | tok_name[ENCODING] = 'ENCODING' |
| 50 | N_TOKENS += 3 |
Meador Inge | 00c7f85 | 2012-01-19 00:44:45 -0600 | [diff] [blame] | 51 | EXACT_TOKEN_TYPES = { |
| 52 | '(': LPAR, |
| 53 | ')': RPAR, |
| 54 | '[': LSQB, |
| 55 | ']': RSQB, |
| 56 | ':': COLON, |
| 57 | ',': COMMA, |
| 58 | ';': SEMI, |
| 59 | '+': PLUS, |
| 60 | '-': MINUS, |
| 61 | '*': STAR, |
| 62 | '/': SLASH, |
| 63 | '|': VBAR, |
| 64 | '&': AMPER, |
| 65 | '<': LESS, |
| 66 | '>': GREATER, |
| 67 | '=': EQUAL, |
| 68 | '.': DOT, |
| 69 | '%': PERCENT, |
| 70 | '{': LBRACE, |
| 71 | '}': RBRACE, |
| 72 | '==': EQEQUAL, |
| 73 | '!=': NOTEQUAL, |
| 74 | '<=': LESSEQUAL, |
| 75 | '>=': GREATEREQUAL, |
| 76 | '~': TILDE, |
| 77 | '^': CIRCUMFLEX, |
| 78 | '<<': LEFTSHIFT, |
| 79 | '>>': RIGHTSHIFT, |
| 80 | '**': DOUBLESTAR, |
| 81 | '+=': PLUSEQUAL, |
| 82 | '-=': MINEQUAL, |
| 83 | '*=': STAREQUAL, |
| 84 | '/=': SLASHEQUAL, |
| 85 | '%=': PERCENTEQUAL, |
| 86 | '&=': AMPEREQUAL, |
| 87 | '|=': VBAREQUAL, |
| 88 | '^=': CIRCUMFLEXEQUAL, |
| 89 | '<<=': LEFTSHIFTEQUAL, |
| 90 | '>>=': RIGHTSHIFTEQUAL, |
| 91 | '**=': DOUBLESTAREQUAL, |
| 92 | '//': DOUBLESLASH, |
| 93 | '//=': DOUBLESLASHEQUAL, |
Benjamin Peterson | d51374e | 2014-04-09 23:55:56 -0400 | [diff] [blame] | 94 | '@': AT, |
| 95 | '@=': ATEQUAL, |
Meador Inge | 00c7f85 | 2012-01-19 00:44:45 -0600 | [diff] [blame] | 96 | } |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 97 | |
Raymond Hettinger | 3fb79c7 | 2010-09-09 07:15:18 +0000 | [diff] [blame] | 98 | class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')): |
Raymond Hettinger | aa17a7f | 2009-04-29 14:21:25 +0000 | [diff] [blame] | 99 | def __repr__(self): |
Raymond Hettinger | a0e7940 | 2010-09-09 08:29:05 +0000 | [diff] [blame] | 100 | annotated_type = '%d (%s)' % (self.type, tok_name[self.type]) |
| 101 | return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' % |
| 102 | self._replace(type=annotated_type)) |
Raymond Hettinger | aa17a7f | 2009-04-29 14:21:25 +0000 | [diff] [blame] | 103 | |
Meador Inge | 00c7f85 | 2012-01-19 00:44:45 -0600 | [diff] [blame] | 104 | @property |
| 105 | def exact_type(self): |
| 106 | if self.type == OP and self.string in EXACT_TOKEN_TYPES: |
| 107 | return EXACT_TOKEN_TYPES[self.string] |
| 108 | else: |
| 109 | return self.type |
| 110 | |
Eric S. Raymond | b08b2d3 | 2001-02-09 11:10:16 +0000 | [diff] [blame] | 111 | def group(*choices): return '(' + '|'.join(choices) + ')' |
Guido van Rossum | 68468eb | 2003-02-27 20:14:51 +0000 | [diff] [blame] | 112 | def any(*choices): return group(*choices) + '*' |
| 113 | def maybe(*choices): return group(*choices) + '?' |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 114 | |
Antoine Pitrou | fd03645 | 2008-08-19 17:56:33 +0000 | [diff] [blame] | 115 | # Note: we use unicode matching for names ("\w") but ascii matching for |
| 116 | # number literals. |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 117 | Whitespace = r'[ \f\t]*' |
| 118 | Comment = r'#[^\r\n]*' |
| 119 | Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment) |
Benjamin Peterson | 33856de | 2010-08-30 14:41:20 +0000 | [diff] [blame] | 120 | Name = r'\w+' |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 121 | |
Antoine Pitrou | fd03645 | 2008-08-19 17:56:33 +0000 | [diff] [blame] | 122 | Hexnumber = r'0[xX][0-9a-fA-F]+' |
Georg Brandl | fceab5a | 2008-01-19 20:08:23 +0000 | [diff] [blame] | 123 | Binnumber = r'0[bB][01]+' |
| 124 | Octnumber = r'0[oO][0-7]+' |
Antoine Pitrou | fd03645 | 2008-08-19 17:56:33 +0000 | [diff] [blame] | 125 | Decnumber = r'(?:0+|[1-9][0-9]*)' |
Guido van Rossum | cd16bf6 | 2007-06-13 18:07:49 +0000 | [diff] [blame] | 126 | Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber) |
Antoine Pitrou | fd03645 | 2008-08-19 17:56:33 +0000 | [diff] [blame] | 127 | Exponent = r'[eE][-+]?[0-9]+' |
| 128 | Pointfloat = group(r'[0-9]+\.[0-9]*', r'\.[0-9]+') + maybe(Exponent) |
| 129 | Expfloat = r'[0-9]+' + Exponent |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 130 | Floatnumber = group(Pointfloat, Expfloat) |
Antoine Pitrou | fd03645 | 2008-08-19 17:56:33 +0000 | [diff] [blame] | 131 | Imagnumber = group(r'[0-9]+[jJ]', Floatnumber + r'[jJ]') |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 132 | Number = group(Imagnumber, Floatnumber, Intnumber) |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 133 | |
Christian Heimes | 0b3847d | 2012-06-20 11:17:58 +0200 | [diff] [blame] | 134 | StringPrefix = r'(?:[bB][rR]?|[rR][bB]?|[uU])?' |
Armin Ronacher | c0eaeca | 2012-03-04 13:07:57 +0000 | [diff] [blame] | 135 | |
Tim Peters | de49583 | 2000-10-07 05:09:39 +0000 | [diff] [blame] | 136 | # Tail end of ' string. |
| 137 | Single = r"[^'\\]*(?:\\.[^'\\]*)*'" |
| 138 | # Tail end of " string. |
| 139 | Double = r'[^"\\]*(?:\\.[^"\\]*)*"' |
| 140 | # Tail end of ''' string. |
| 141 | Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''" |
| 142 | # Tail end of """ string. |
| 143 | Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""' |
Armin Ronacher | c0eaeca | 2012-03-04 13:07:57 +0000 | [diff] [blame] | 144 | Triple = group(StringPrefix + "'''", StringPrefix + '"""') |
Tim Peters | de49583 | 2000-10-07 05:09:39 +0000 | [diff] [blame] | 145 | # Single-line ' or " string. |
Armin Ronacher | c0eaeca | 2012-03-04 13:07:57 +0000 | [diff] [blame] | 146 | String = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'", |
| 147 | StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"') |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 148 | |
Tim Peters | de49583 | 2000-10-07 05:09:39 +0000 | [diff] [blame] | 149 | # Because of leftmost-then-longest match semantics, be sure to put the |
| 150 | # longest operators first (e.g., if = came before ==, == would get |
| 151 | # recognized as two instances of =). |
Guido van Rossum | b053cd8 | 2006-08-24 03:53:23 +0000 | [diff] [blame] | 152 | Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=", |
Neal Norwitz | c150536 | 2006-12-28 06:47:50 +0000 | [diff] [blame] | 153 | r"//=?", r"->", |
Benjamin Peterson | d51374e | 2014-04-09 23:55:56 -0400 | [diff] [blame] | 154 | r"[+\-*/%&@|^=<>]=?", |
Tim Peters | de49583 | 2000-10-07 05:09:39 +0000 | [diff] [blame] | 155 | r"~") |
Thomas Wouters | e1519a1 | 2000-08-24 21:44:52 +0000 | [diff] [blame] | 156 | |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 157 | Bracket = '[][(){}]' |
Georg Brandl | dde0028 | 2007-03-18 19:01:53 +0000 | [diff] [blame] | 158 | Special = group(r'\r?\n', r'\.\.\.', r'[:;.,@]') |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 159 | Funny = group(Operator, Bracket, Special) |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 160 | |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 161 | PlainToken = group(Number, Funny, String, Name) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 162 | Token = Ignore + PlainToken |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 163 | |
Tim Peters | de49583 | 2000-10-07 05:09:39 +0000 | [diff] [blame] | 164 | # First (or only) line of ' or " string. |
Armin Ronacher | c0eaeca | 2012-03-04 13:07:57 +0000 | [diff] [blame] | 165 | ContStr = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" + |
Ka-Ping Yee | 1ff08b1 | 2001-01-15 22:04:30 +0000 | [diff] [blame] | 166 | group("'", r'\\\r?\n'), |
Armin Ronacher | c0eaeca | 2012-03-04 13:07:57 +0000 | [diff] [blame] | 167 | StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' + |
Ka-Ping Yee | 1ff08b1 | 2001-01-15 22:04:30 +0000 | [diff] [blame] | 168 | group('"', r'\\\r?\n')) |
Ezio Melotti | 2cc3b4b | 2012-11-03 17:38:43 +0200 | [diff] [blame] | 169 | PseudoExtras = group(r'\\\r?\n|\Z', Comment, Triple) |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 170 | PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name) |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 171 | |
Benjamin Peterson | 33856de | 2010-08-30 14:41:20 +0000 | [diff] [blame] | 172 | def _compile(expr): |
| 173 | return re.compile(expr, re.UNICODE) |
| 174 | |
Antoine Pitrou | 10a99b0 | 2011-10-11 15:45:56 +0200 | [diff] [blame] | 175 | endpats = {"'": Single, '"': Double, |
| 176 | "'''": Single3, '"""': Double3, |
| 177 | "r'''": Single3, 'r"""': Double3, |
| 178 | "b'''": Single3, 'b"""': Double3, |
Antoine Pitrou | 10a99b0 | 2011-10-11 15:45:56 +0200 | [diff] [blame] | 179 | "R'''": Single3, 'R"""': Double3, |
| 180 | "B'''": Single3, 'B"""': Double3, |
Armin Ronacher | c0eaeca | 2012-03-04 13:07:57 +0000 | [diff] [blame] | 181 | "br'''": Single3, 'br"""': Double3, |
Antoine Pitrou | 10a99b0 | 2011-10-11 15:45:56 +0200 | [diff] [blame] | 182 | "bR'''": Single3, 'bR"""': Double3, |
| 183 | "Br'''": Single3, 'Br"""': Double3, |
| 184 | "BR'''": Single3, 'BR"""': Double3, |
Armin Ronacher | c0eaeca | 2012-03-04 13:07:57 +0000 | [diff] [blame] | 185 | "rb'''": Single3, 'rb"""': Double3, |
| 186 | "Rb'''": Single3, 'Rb"""': Double3, |
| 187 | "rB'''": Single3, 'rB"""': Double3, |
| 188 | "RB'''": Single3, 'RB"""': Double3, |
Armin Ronacher | 6ecf77b | 2012-03-04 12:04:06 +0000 | [diff] [blame] | 189 | "u'''": Single3, 'u"""': Double3, |
Armin Ronacher | 6ecf77b | 2012-03-04 12:04:06 +0000 | [diff] [blame] | 190 | "U'''": Single3, 'U"""': Double3, |
Armin Ronacher | 6ecf77b | 2012-03-04 12:04:06 +0000 | [diff] [blame] | 191 | 'r': None, 'R': None, 'b': None, 'B': None, |
| 192 | 'u': None, 'U': None} |
Guido van Rossum | 4d8e859 | 1992-01-01 19:34:47 +0000 | [diff] [blame] | 193 | |
Guido van Rossum | 9d6897a | 2002-08-24 06:54:19 +0000 | [diff] [blame] | 194 | triple_quoted = {} |
| 195 | for t in ("'''", '"""', |
| 196 | "r'''", 'r"""', "R'''", 'R"""', |
Guido van Rossum | 4fe72f9 | 2007-11-12 17:40:10 +0000 | [diff] [blame] | 197 | "b'''", 'b"""', "B'''", 'B"""', |
| 198 | "br'''", 'br"""', "Br'''", 'Br"""', |
Armin Ronacher | 6ecf77b | 2012-03-04 12:04:06 +0000 | [diff] [blame] | 199 | "bR'''", 'bR"""', "BR'''", 'BR"""', |
Armin Ronacher | c0eaeca | 2012-03-04 13:07:57 +0000 | [diff] [blame] | 200 | "rb'''", 'rb"""', "rB'''", 'rB"""', |
| 201 | "Rb'''", 'Rb"""', "RB'''", 'RB"""', |
Armin Ronacher | 6ecf77b | 2012-03-04 12:04:06 +0000 | [diff] [blame] | 202 | "u'''", 'u"""', "U'''", 'U"""', |
Christian Heimes | 0b3847d | 2012-06-20 11:17:58 +0200 | [diff] [blame] | 203 | ): |
Guido van Rossum | 9d6897a | 2002-08-24 06:54:19 +0000 | [diff] [blame] | 204 | triple_quoted[t] = t |
| 205 | single_quoted = {} |
| 206 | for t in ("'", '"', |
| 207 | "r'", 'r"', "R'", 'R"', |
Guido van Rossum | 4fe72f9 | 2007-11-12 17:40:10 +0000 | [diff] [blame] | 208 | "b'", 'b"', "B'", 'B"', |
| 209 | "br'", 'br"', "Br'", 'Br"', |
Armin Ronacher | 6ecf77b | 2012-03-04 12:04:06 +0000 | [diff] [blame] | 210 | "bR'", 'bR"', "BR'", 'BR"' , |
Armin Ronacher | c0eaeca | 2012-03-04 13:07:57 +0000 | [diff] [blame] | 211 | "rb'", 'rb"', "rB'", 'rB"', |
| 212 | "Rb'", 'Rb"', "RB'", 'RB"' , |
Armin Ronacher | 6ecf77b | 2012-03-04 12:04:06 +0000 | [diff] [blame] | 213 | "u'", 'u"', "U'", 'U"', |
Christian Heimes | 0b3847d | 2012-06-20 11:17:58 +0200 | [diff] [blame] | 214 | ): |
Guido van Rossum | 9d6897a | 2002-08-24 06:54:19 +0000 | [diff] [blame] | 215 | single_quoted[t] = t |
| 216 | |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 217 | tabsize = 8 |
Fred Drake | 9b8d801 | 2000-08-17 04:45:13 +0000 | [diff] [blame] | 218 | |
Ka-Ping Yee | 28c62bb | 2001-03-23 05:22:49 +0000 | [diff] [blame] | 219 | class TokenError(Exception): pass |
| 220 | |
| 221 | class StopTokenizing(Exception): pass |
Fred Drake | 9b8d801 | 2000-08-17 04:45:13 +0000 | [diff] [blame] | 222 | |
Tim Peters | 5ca576e | 2001-06-18 22:08:13 +0000 | [diff] [blame] | 223 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 224 | class Untokenizer: |
| 225 | |
| 226 | def __init__(self): |
| 227 | self.tokens = [] |
| 228 | self.prev_row = 1 |
| 229 | self.prev_col = 0 |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 230 | self.encoding = None |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 231 | |
| 232 | def add_whitespace(self, start): |
| 233 | row, col = start |
Terry Jan Reedy | 5e6db31 | 2014-02-17 16:45:48 -0500 | [diff] [blame] | 234 | if row < self.prev_row or row == self.prev_row and col < self.prev_col: |
| 235 | raise ValueError("start ({},{}) precedes previous end ({},{})" |
| 236 | .format(row, col, self.prev_row, self.prev_col)) |
Terry Jan Reedy | 9dc3a36 | 2014-02-23 23:33:08 -0500 | [diff] [blame] | 237 | row_offset = row - self.prev_row |
Terry Jan Reedy | f106f8f | 2014-02-23 23:39:57 -0500 | [diff] [blame] | 238 | if row_offset: |
Terry Jan Reedy | 9dc3a36 | 2014-02-23 23:33:08 -0500 | [diff] [blame] | 239 | self.tokens.append("\\\n" * row_offset) |
| 240 | self.prev_col = 0 |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 241 | col_offset = col - self.prev_col |
| 242 | if col_offset: |
| 243 | self.tokens.append(" " * col_offset) |
| 244 | |
| 245 | def untokenize(self, iterable): |
Terry Jan Reedy | 5b8d2c3 | 2014-02-17 23:12:16 -0500 | [diff] [blame] | 246 | it = iter(iterable) |
| 247 | for t in it: |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 248 | if len(t) == 2: |
Terry Jan Reedy | 5b8d2c3 | 2014-02-17 23:12:16 -0500 | [diff] [blame] | 249 | self.compat(t, it) |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 250 | break |
| 251 | tok_type, token, start, end, line = t |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 252 | if tok_type == ENCODING: |
| 253 | self.encoding = token |
| 254 | continue |
Terry Jan Reedy | 9dc3a36 | 2014-02-23 23:33:08 -0500 | [diff] [blame] | 255 | if tok_type == ENDMARKER: |
| 256 | break |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 257 | self.add_whitespace(start) |
| 258 | self.tokens.append(token) |
| 259 | self.prev_row, self.prev_col = end |
| 260 | if tok_type in (NEWLINE, NL): |
| 261 | self.prev_row += 1 |
| 262 | self.prev_col = 0 |
| 263 | return "".join(self.tokens) |
| 264 | |
| 265 | def compat(self, token, iterable): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 266 | indents = [] |
| 267 | toks_append = self.tokens.append |
Terry Jan Reedy | 5b8d2c3 | 2014-02-17 23:12:16 -0500 | [diff] [blame] | 268 | startline = token[0] in (NEWLINE, NL) |
Christian Heimes | ba4af49 | 2008-03-28 00:55:15 +0000 | [diff] [blame] | 269 | prevstring = False |
Terry Jan Reedy | 5b8d2c3 | 2014-02-17 23:12:16 -0500 | [diff] [blame] | 270 | |
| 271 | for tok in chain([token], iterable): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 272 | toknum, tokval = tok[:2] |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 273 | if toknum == ENCODING: |
| 274 | self.encoding = tokval |
| 275 | continue |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 276 | |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame^] | 277 | if toknum in (NAME, NUMBER, ASYNC, AWAIT): |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 278 | tokval += ' ' |
| 279 | |
Christian Heimes | ba4af49 | 2008-03-28 00:55:15 +0000 | [diff] [blame] | 280 | # Insert a space between two consecutive strings |
| 281 | if toknum == STRING: |
| 282 | if prevstring: |
| 283 | tokval = ' ' + tokval |
| 284 | prevstring = True |
| 285 | else: |
| 286 | prevstring = False |
| 287 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 288 | if toknum == INDENT: |
| 289 | indents.append(tokval) |
| 290 | continue |
| 291 | elif toknum == DEDENT: |
| 292 | indents.pop() |
| 293 | continue |
| 294 | elif toknum in (NEWLINE, NL): |
| 295 | startline = True |
| 296 | elif startline and indents: |
| 297 | toks_append(indents[-1]) |
| 298 | startline = False |
| 299 | toks_append(tokval) |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 300 | |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 301 | |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 302 | def untokenize(iterable): |
| 303 | """Transform tokens back into Python source code. |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 304 | It returns a bytes object, encoded using the ENCODING |
| 305 | token, which is the first token sequence output by tokenize. |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 306 | |
| 307 | Each element returned by the iterable must be a token sequence |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 308 | with at least two elements, a token number and token value. If |
| 309 | only two tokens are passed, the resulting output is poor. |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 310 | |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 311 | Round-trip invariant for full input: |
| 312 | Untokenized source will match input source exactly |
| 313 | |
| 314 | Round-trip invariant for limited intput: |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 315 | # Output bytes will tokenize the back to the input |
| 316 | t1 = [tok[:2] for tok in tokenize(f.readline)] |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 317 | newcode = untokenize(t1) |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 318 | readline = BytesIO(newcode).readline |
| 319 | t2 = [tok[:2] for tok in tokenize(readline)] |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 320 | assert t1 == t2 |
| 321 | """ |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 322 | ut = Untokenizer() |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 323 | out = ut.untokenize(iterable) |
| 324 | if ut.encoding is not None: |
| 325 | out = out.encode(ut.encoding) |
| 326 | return out |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 327 | |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 328 | |
Benjamin Peterson | d3afada | 2009-10-09 21:43:09 +0000 | [diff] [blame] | 329 | def _get_normal_name(orig_enc): |
| 330 | """Imitates get_normal_name in tokenizer.c.""" |
| 331 | # Only care about the first 12 characters. |
| 332 | enc = orig_enc[:12].lower().replace("_", "-") |
| 333 | if enc == "utf-8" or enc.startswith("utf-8-"): |
| 334 | return "utf-8" |
| 335 | if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \ |
| 336 | enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")): |
| 337 | return "iso-8859-1" |
| 338 | return orig_enc |
| 339 | |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 340 | def detect_encoding(readline): |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 341 | """ |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 342 | The detect_encoding() function is used to detect the encoding that should |
Ezio Melotti | 4bcc796 | 2013-11-25 05:14:51 +0200 | [diff] [blame] | 343 | be used to decode a Python source file. It requires one argument, readline, |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 344 | in the same way as the tokenize() generator. |
| 345 | |
| 346 | It will call readline a maximum of twice, and return the encoding used |
Florent Xicluna | 43e4ea1 | 2010-09-03 19:54:02 +0000 | [diff] [blame] | 347 | (as a string) and a list of any lines (left as bytes) it has read in. |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 348 | |
| 349 | It detects the encoding from the presence of a utf-8 bom or an encoding |
Florent Xicluna | 43e4ea1 | 2010-09-03 19:54:02 +0000 | [diff] [blame] | 350 | cookie as specified in pep-0263. If both a bom and a cookie are present, |
| 351 | but disagree, a SyntaxError will be raised. If the encoding cookie is an |
| 352 | invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found, |
Benjamin Peterson | 689a558 | 2010-03-18 22:29:52 +0000 | [diff] [blame] | 353 | 'utf-8-sig' is returned. |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 354 | |
| 355 | If no encoding is specified, then the default of 'utf-8' will be returned. |
| 356 | """ |
Brett Cannon | c33f3f2 | 2012-04-20 13:23:54 -0400 | [diff] [blame] | 357 | try: |
| 358 | filename = readline.__self__.name |
| 359 | except AttributeError: |
| 360 | filename = None |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 361 | bom_found = False |
| 362 | encoding = None |
Benjamin Peterson | 689a558 | 2010-03-18 22:29:52 +0000 | [diff] [blame] | 363 | default = 'utf-8' |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 364 | def read_or_stop(): |
| 365 | try: |
| 366 | return readline() |
| 367 | except StopIteration: |
| 368 | return b'' |
| 369 | |
| 370 | def find_cookie(line): |
| 371 | try: |
Martin v. Löwis | 63674f4 | 2012-04-20 14:36:47 +0200 | [diff] [blame] | 372 | # Decode as UTF-8. Either the line is an encoding declaration, |
| 373 | # in which case it should be pure ASCII, or it must be UTF-8 |
| 374 | # per default encoding. |
| 375 | line_string = line.decode('utf-8') |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 376 | except UnicodeDecodeError: |
Brett Cannon | c33f3f2 | 2012-04-20 13:23:54 -0400 | [diff] [blame] | 377 | msg = "invalid or missing encoding declaration" |
| 378 | if filename is not None: |
| 379 | msg = '{} for {!r}'.format(msg, filename) |
| 380 | raise SyntaxError(msg) |
Benjamin Peterson | 433f32c | 2008-12-12 01:25:05 +0000 | [diff] [blame] | 381 | |
Serhiy Storchaka | dafea85 | 2013-09-16 23:51:56 +0300 | [diff] [blame] | 382 | match = cookie_re.match(line_string) |
| 383 | if not match: |
Benjamin Peterson | 433f32c | 2008-12-12 01:25:05 +0000 | [diff] [blame] | 384 | return None |
Serhiy Storchaka | dafea85 | 2013-09-16 23:51:56 +0300 | [diff] [blame] | 385 | encoding = _get_normal_name(match.group(1)) |
Benjamin Peterson | 433f32c | 2008-12-12 01:25:05 +0000 | [diff] [blame] | 386 | try: |
| 387 | codec = lookup(encoding) |
| 388 | except LookupError: |
| 389 | # This behaviour mimics the Python interpreter |
Brett Cannon | c33f3f2 | 2012-04-20 13:23:54 -0400 | [diff] [blame] | 390 | if filename is None: |
| 391 | msg = "unknown encoding: " + encoding |
| 392 | else: |
| 393 | msg = "unknown encoding for {!r}: {}".format(filename, |
| 394 | encoding) |
| 395 | raise SyntaxError(msg) |
Benjamin Peterson | 433f32c | 2008-12-12 01:25:05 +0000 | [diff] [blame] | 396 | |
Benjamin Peterson | 1613ed8 | 2010-03-18 22:34:15 +0000 | [diff] [blame] | 397 | if bom_found: |
Florent Xicluna | 11f0b41 | 2012-07-07 12:13:35 +0200 | [diff] [blame] | 398 | if encoding != 'utf-8': |
Benjamin Peterson | 1613ed8 | 2010-03-18 22:34:15 +0000 | [diff] [blame] | 399 | # This behaviour mimics the Python interpreter |
Brett Cannon | c33f3f2 | 2012-04-20 13:23:54 -0400 | [diff] [blame] | 400 | if filename is None: |
| 401 | msg = 'encoding problem: utf-8' |
| 402 | else: |
| 403 | msg = 'encoding problem for {!r}: utf-8'.format(filename) |
| 404 | raise SyntaxError(msg) |
Benjamin Peterson | 1613ed8 | 2010-03-18 22:34:15 +0000 | [diff] [blame] | 405 | encoding += '-sig' |
Benjamin Peterson | 433f32c | 2008-12-12 01:25:05 +0000 | [diff] [blame] | 406 | return encoding |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 407 | |
| 408 | first = read_or_stop() |
Benjamin Peterson | 433f32c | 2008-12-12 01:25:05 +0000 | [diff] [blame] | 409 | if first.startswith(BOM_UTF8): |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 410 | bom_found = True |
| 411 | first = first[3:] |
Benjamin Peterson | 689a558 | 2010-03-18 22:29:52 +0000 | [diff] [blame] | 412 | default = 'utf-8-sig' |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 413 | if not first: |
Benjamin Peterson | 689a558 | 2010-03-18 22:29:52 +0000 | [diff] [blame] | 414 | return default, [] |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 415 | |
| 416 | encoding = find_cookie(first) |
| 417 | if encoding: |
| 418 | return encoding, [first] |
Serhiy Storchaka | 768c16c | 2014-01-09 18:36:09 +0200 | [diff] [blame] | 419 | if not blank_re.match(first): |
| 420 | return default, [first] |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 421 | |
| 422 | second = read_or_stop() |
| 423 | if not second: |
Benjamin Peterson | 689a558 | 2010-03-18 22:29:52 +0000 | [diff] [blame] | 424 | return default, [first] |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 425 | |
| 426 | encoding = find_cookie(second) |
| 427 | if encoding: |
| 428 | return encoding, [first, second] |
| 429 | |
Benjamin Peterson | 689a558 | 2010-03-18 22:29:52 +0000 | [diff] [blame] | 430 | return default, [first, second] |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 431 | |
| 432 | |
Victor Stinner | 58c0752 | 2010-11-09 01:08:59 +0000 | [diff] [blame] | 433 | def open(filename): |
| 434 | """Open a file in read only mode using the encoding detected by |
| 435 | detect_encoding(). |
| 436 | """ |
Victor Stinner | 9691750 | 2014-12-05 10:17:10 +0100 | [diff] [blame] | 437 | buffer = _builtin_open(filename, 'rb') |
Victor Stinner | 58c0752 | 2010-11-09 01:08:59 +0000 | [diff] [blame] | 438 | encoding, lines = detect_encoding(buffer.readline) |
| 439 | buffer.seek(0) |
| 440 | text = TextIOWrapper(buffer, encoding, line_buffering=True) |
| 441 | text.mode = 'r' |
| 442 | return text |
| 443 | |
| 444 | |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 445 | def tokenize(readline): |
| 446 | """ |
| 447 | The tokenize() generator requires one argment, readline, which |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 448 | must be a callable object which provides the same interface as the |
Florent Xicluna | 43e4ea1 | 2010-09-03 19:54:02 +0000 | [diff] [blame] | 449 | readline() method of built-in file objects. Each call to the function |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 450 | should return one line of input as bytes. Alternately, readline |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 451 | can be a callable function terminating with StopIteration: |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 452 | readline = open(myfile, 'rb').__next__ # Example of alternate readline |
Tim Peters | 8ac1495 | 2002-05-23 15:15:30 +0000 | [diff] [blame] | 453 | |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 454 | The generator produces 5-tuples with these members: the token type; the |
| 455 | token string; a 2-tuple (srow, scol) of ints specifying the row and |
| 456 | column where the token begins in the source; a 2-tuple (erow, ecol) of |
| 457 | ints specifying the row and column where the token ends in the source; |
Florent Xicluna | 43e4ea1 | 2010-09-03 19:54:02 +0000 | [diff] [blame] | 458 | 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] | 459 | logical line; continuation lines are included. |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 460 | |
| 461 | The first token sequence will always be an ENCODING token |
| 462 | which tells you which encoding was used to decode the bytes stream. |
Raymond Hettinger | d1fa3db | 2002-05-15 02:56:03 +0000 | [diff] [blame] | 463 | """ |
Benjamin Peterson | 21db77e | 2009-11-14 16:27:26 +0000 | [diff] [blame] | 464 | # This import is here to avoid problems when the itertools module is not |
| 465 | # built yet and tokenize is imported. |
Benjamin Peterson | 81dd8b9 | 2009-11-14 18:09:17 +0000 | [diff] [blame] | 466 | from itertools import chain, repeat |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 467 | encoding, consumed = detect_encoding(readline) |
Benjamin Peterson | 81dd8b9 | 2009-11-14 18:09:17 +0000 | [diff] [blame] | 468 | rl_gen = iter(readline, b"") |
| 469 | empty = repeat(b"") |
| 470 | return _tokenize(chain(consumed, rl_gen, empty).__next__, encoding) |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 471 | |
| 472 | |
| 473 | def _tokenize(readline, encoding): |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 474 | lnum = parenlev = continued = 0 |
Benjamin Peterson | 33856de | 2010-08-30 14:41:20 +0000 | [diff] [blame] | 475 | numchars = '0123456789' |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 476 | contstr, needcont = '', 0 |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 477 | contline = None |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 478 | indents = [0] |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 479 | |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame^] | 480 | # 'stashed' and 'ctx' are used for async/await parsing |
| 481 | stashed = None |
| 482 | ctx = [('sync', 0)] |
| 483 | |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 484 | if encoding is not None: |
Benjamin Peterson | 689a558 | 2010-03-18 22:29:52 +0000 | [diff] [blame] | 485 | if encoding == "utf-8-sig": |
| 486 | # BOM will already have been stripped. |
| 487 | encoding = "utf-8" |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 488 | yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '') |
Benjamin Peterson | 0fe1438 | 2008-06-05 23:07:42 +0000 | [diff] [blame] | 489 | while True: # loop over lines in stream |
Raymond Hettinger | 68c0453 | 2005-06-10 11:05:19 +0000 | [diff] [blame] | 490 | try: |
| 491 | line = readline() |
| 492 | except StopIteration: |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 493 | line = b'' |
| 494 | |
| 495 | if encoding is not None: |
| 496 | line = line.decode(encoding) |
Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +0000 | [diff] [blame] | 497 | lnum += 1 |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 498 | pos, max = 0, len(line) |
| 499 | |
| 500 | if contstr: # continued string |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 501 | if not line: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 502 | raise TokenError("EOF in multi-line string", strstart) |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 503 | endmatch = endprog.match(line) |
| 504 | if endmatch: |
| 505 | pos = end = endmatch.end(0) |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 506 | yield TokenInfo(STRING, contstr + line[:end], |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 507 | strstart, (lnum, end), contline + line) |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 508 | contstr, needcont = '', 0 |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 509 | contline = None |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 510 | elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n': |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 511 | yield TokenInfo(ERRORTOKEN, contstr + line, |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 512 | strstart, (lnum, len(line)), contline) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 513 | contstr = '' |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 514 | contline = None |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 515 | continue |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 516 | else: |
| 517 | contstr = contstr + line |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 518 | contline = contline + line |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 519 | continue |
| 520 | |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 521 | elif parenlev == 0 and not continued: # new statement |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 522 | if not line: break |
| 523 | column = 0 |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 524 | while pos < max: # measure leading whitespace |
Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +0000 | [diff] [blame] | 525 | if line[pos] == ' ': |
| 526 | column += 1 |
| 527 | elif line[pos] == '\t': |
| 528 | column = (column//tabsize + 1)*tabsize |
| 529 | elif line[pos] == '\f': |
| 530 | column = 0 |
| 531 | else: |
| 532 | break |
| 533 | pos += 1 |
| 534 | if pos == max: |
| 535 | break |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 536 | |
| 537 | if line[pos] in '#\r\n': # skip comments or blank lines |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 538 | if line[pos] == '#': |
| 539 | comment_token = line[pos:].rstrip('\r\n') |
| 540 | nl_pos = pos + len(comment_token) |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 541 | yield TokenInfo(COMMENT, comment_token, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 542 | (lnum, pos), (lnum, pos + len(comment_token)), line) |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 543 | yield TokenInfo(NL, line[nl_pos:], |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 544 | (lnum, nl_pos), (lnum, len(line)), line) |
| 545 | else: |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 546 | yield TokenInfo((NL, COMMENT)[line[pos] == '#'], line[pos:], |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 547 | (lnum, pos), (lnum, len(line)), line) |
| 548 | continue |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 549 | |
| 550 | if column > indents[-1]: # count indents or dedents |
| 551 | indents.append(column) |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 552 | yield TokenInfo(INDENT, line[:pos], (lnum, 0), (lnum, pos), line) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 553 | while column < indents[-1]: |
Raymond Hettinger | da99d1c | 2005-06-21 07:43:58 +0000 | [diff] [blame] | 554 | if column not in indents: |
| 555 | raise IndentationError( |
Thomas Wouters | 00ee7ba | 2006-08-21 19:07:27 +0000 | [diff] [blame] | 556 | "unindent does not match any outer indentation level", |
| 557 | ("<tokenize>", lnum, pos, line)) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 558 | indents = indents[:-1] |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame^] | 559 | |
| 560 | cur_indent = indents[-1] |
| 561 | while len(ctx) > 1 and ctx[-1][1] >= cur_indent: |
| 562 | ctx.pop() |
| 563 | |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 564 | yield TokenInfo(DEDENT, '', (lnum, pos), (lnum, pos), line) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 565 | |
| 566 | else: # continued statement |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 567 | if not line: |
Collin Winter | ce36ad8 | 2007-08-30 01:19:48 +0000 | [diff] [blame] | 568 | raise TokenError("EOF in multi-line statement", (lnum, 0)) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 569 | continued = 0 |
| 570 | |
| 571 | while pos < max: |
Antoine Pitrou | 10a99b0 | 2011-10-11 15:45:56 +0200 | [diff] [blame] | 572 | pseudomatch = _compile(PseudoToken).match(line, pos) |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 573 | if pseudomatch: # scan for tokens |
| 574 | start, end = pseudomatch.span(1) |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 575 | spos, epos, pos = (lnum, start), (lnum, end), end |
Ezio Melotti | 2cc3b4b | 2012-11-03 17:38:43 +0200 | [diff] [blame] | 576 | if start == end: |
| 577 | continue |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 578 | token, initial = line[start:end], line[start] |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 579 | |
Georg Brandl | dde0028 | 2007-03-18 19:01:53 +0000 | [diff] [blame] | 580 | if (initial in numchars or # ordinary number |
| 581 | (initial == '.' and token != '.' and token != '...')): |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 582 | yield TokenInfo(NUMBER, token, spos, epos, line) |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 583 | elif initial in '\r\n': |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame^] | 584 | if stashed: |
| 585 | yield stashed |
| 586 | stashed = None |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 587 | yield TokenInfo(NL if parenlev > 0 else NEWLINE, |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 588 | token, spos, epos, line) |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 589 | elif initial == '#': |
Thomas Wouters | 89f507f | 2006-12-13 04:49:30 +0000 | [diff] [blame] | 590 | assert not token.endswith("\n") |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame^] | 591 | if stashed: |
| 592 | yield stashed |
| 593 | stashed = None |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 594 | yield TokenInfo(COMMENT, token, spos, epos, line) |
Guido van Rossum | 9d6897a | 2002-08-24 06:54:19 +0000 | [diff] [blame] | 595 | elif token in triple_quoted: |
Antoine Pitrou | 10a99b0 | 2011-10-11 15:45:56 +0200 | [diff] [blame] | 596 | endprog = _compile(endpats[token]) |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 597 | endmatch = endprog.match(line, pos) |
| 598 | if endmatch: # all on one line |
| 599 | pos = endmatch.end(0) |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 600 | token = line[start:pos] |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 601 | yield TokenInfo(STRING, token, spos, (lnum, pos), line) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 602 | else: |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 603 | strstart = (lnum, start) # multiple lines |
| 604 | contstr = line[start:] |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 605 | contline = line |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 606 | break |
Guido van Rossum | 9d6897a | 2002-08-24 06:54:19 +0000 | [diff] [blame] | 607 | elif initial in single_quoted or \ |
| 608 | token[:2] in single_quoted or \ |
| 609 | token[:3] in single_quoted: |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 610 | if token[-1] == '\n': # continued string |
Guido van Rossum | 1aec323 | 1997-04-08 14:24:39 +0000 | [diff] [blame] | 611 | strstart = (lnum, start) |
Antoine Pitrou | 10a99b0 | 2011-10-11 15:45:56 +0200 | [diff] [blame] | 612 | endprog = _compile(endpats[initial] or |
| 613 | endpats[token[1]] or |
| 614 | endpats[token[2]]) |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 615 | contstr, needcont = line[start:], 1 |
Guido van Rossum | a90c78b | 1998-04-03 16:05:38 +0000 | [diff] [blame] | 616 | contline = line |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 617 | break |
| 618 | else: # ordinary string |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 619 | yield TokenInfo(STRING, token, spos, epos, line) |
Benjamin Peterson | 33856de | 2010-08-30 14:41:20 +0000 | [diff] [blame] | 620 | elif initial.isidentifier(): # ordinary name |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame^] | 621 | if token in ('async', 'await'): |
| 622 | if ctx[-1][0] == 'async' and ctx[-1][1] < indents[-1]: |
| 623 | yield TokenInfo( |
| 624 | ASYNC if token == 'async' else AWAIT, |
| 625 | token, spos, epos, line) |
| 626 | continue |
| 627 | |
| 628 | tok = TokenInfo(NAME, token, spos, epos, line) |
| 629 | if token == 'async' and not stashed: |
| 630 | stashed = tok |
| 631 | continue |
| 632 | |
| 633 | if token == 'def': |
| 634 | if (stashed |
| 635 | and stashed.type == NAME |
| 636 | and stashed.string == 'async'): |
| 637 | |
| 638 | ctx.append(('async', indents[-1])) |
| 639 | |
| 640 | yield TokenInfo(ASYNC, stashed.string, |
| 641 | stashed.start, stashed.end, |
| 642 | stashed.line) |
| 643 | stashed = None |
| 644 | else: |
| 645 | ctx.append(('sync', indents[-1])) |
| 646 | |
| 647 | if stashed: |
| 648 | yield stashed |
| 649 | stashed = None |
| 650 | |
| 651 | yield tok |
Guido van Rossum | 3b63177 | 1997-10-27 20:44:15 +0000 | [diff] [blame] | 652 | elif initial == '\\': # continued stmt |
| 653 | continued = 1 |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 654 | else: |
Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +0000 | [diff] [blame] | 655 | if initial in '([{': |
| 656 | parenlev += 1 |
| 657 | elif initial in ')]}': |
| 658 | parenlev -= 1 |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame^] | 659 | if stashed: |
| 660 | yield stashed |
| 661 | stashed = None |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 662 | yield TokenInfo(OP, token, spos, epos, line) |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 663 | else: |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 664 | yield TokenInfo(ERRORTOKEN, line[pos], |
Guido van Rossum | de65527 | 1997-04-09 17:15:54 +0000 | [diff] [blame] | 665 | (lnum, pos), (lnum, pos+1), line) |
Benjamin Peterson | a0dfa82 | 2009-11-13 02:25:08 +0000 | [diff] [blame] | 666 | pos += 1 |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 667 | |
Yury Selivanov | 7544508 | 2015-05-11 22:57:16 -0400 | [diff] [blame^] | 668 | if stashed: |
| 669 | yield stashed |
| 670 | stashed = None |
| 671 | |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 672 | for indent in indents[1:]: # pop remaining indent levels |
Raymond Hettinger | a48db39 | 2009-04-29 00:34:27 +0000 | [diff] [blame] | 673 | yield TokenInfo(DEDENT, '', (lnum, 0), (lnum, 0), '') |
| 674 | yield TokenInfo(ENDMARKER, '', (lnum, 0), (lnum, 0), '') |
Guido van Rossum | fc6f533 | 1997-03-07 00:21:12 +0000 | [diff] [blame] | 675 | |
Trent Nelson | 428de65 | 2008-03-18 22:41:35 +0000 | [diff] [blame] | 676 | |
| 677 | # An undocumented, backwards compatible, API for all the places in the standard |
| 678 | # library that expect to be able to use tokenize with strings |
| 679 | def generate_tokens(readline): |
| 680 | return _tokenize(readline, None) |
Raymond Hettinger | 6c60d09 | 2010-09-09 04:32:39 +0000 | [diff] [blame] | 681 | |
Meador Inge | 14c0f03 | 2011-10-07 08:53:38 -0500 | [diff] [blame] | 682 | def main(): |
| 683 | import argparse |
| 684 | |
| 685 | # Helper error handling routines |
| 686 | def perror(message): |
| 687 | print(message, file=sys.stderr) |
| 688 | |
| 689 | def error(message, filename=None, location=None): |
| 690 | if location: |
| 691 | args = (filename,) + location + (message,) |
| 692 | perror("%s:%d:%d: error: %s" % args) |
| 693 | elif filename: |
| 694 | perror("%s: error: %s" % (filename, message)) |
| 695 | else: |
| 696 | perror("error: %s" % message) |
| 697 | sys.exit(1) |
| 698 | |
| 699 | # Parse the arguments and options |
| 700 | parser = argparse.ArgumentParser(prog='python -m tokenize') |
| 701 | parser.add_argument(dest='filename', nargs='?', |
| 702 | metavar='filename.py', |
| 703 | help='the file to tokenize; defaults to stdin') |
Meador Inge | 00c7f85 | 2012-01-19 00:44:45 -0600 | [diff] [blame] | 704 | parser.add_argument('-e', '--exact', dest='exact', action='store_true', |
| 705 | help='display token names using the exact type') |
Meador Inge | 14c0f03 | 2011-10-07 08:53:38 -0500 | [diff] [blame] | 706 | args = parser.parse_args() |
| 707 | |
| 708 | try: |
| 709 | # Tokenize the input |
| 710 | if args.filename: |
| 711 | filename = args.filename |
Victor Stinner | 9691750 | 2014-12-05 10:17:10 +0100 | [diff] [blame] | 712 | with _builtin_open(filename, 'rb') as f: |
Meador Inge | 14c0f03 | 2011-10-07 08:53:38 -0500 | [diff] [blame] | 713 | tokens = list(tokenize(f.readline)) |
| 714 | else: |
| 715 | filename = "<stdin>" |
| 716 | tokens = _tokenize(sys.stdin.readline, None) |
| 717 | |
| 718 | # Output the tokenization |
| 719 | for token in tokens: |
Meador Inge | 00c7f85 | 2012-01-19 00:44:45 -0600 | [diff] [blame] | 720 | token_type = token.type |
| 721 | if args.exact: |
| 722 | token_type = token.exact_type |
Meador Inge | 14c0f03 | 2011-10-07 08:53:38 -0500 | [diff] [blame] | 723 | token_range = "%d,%d-%d,%d:" % (token.start + token.end) |
| 724 | print("%-20s%-15s%-15r" % |
Meador Inge | 00c7f85 | 2012-01-19 00:44:45 -0600 | [diff] [blame] | 725 | (token_range, tok_name[token_type], token.string)) |
Meador Inge | 14c0f03 | 2011-10-07 08:53:38 -0500 | [diff] [blame] | 726 | except IndentationError as err: |
| 727 | line, column = err.args[1][1:3] |
| 728 | error(err.args[0], filename, (line, column)) |
| 729 | except TokenError as err: |
| 730 | line, column = err.args[1] |
| 731 | error(err.args[0], filename, (line, column)) |
| 732 | except SyntaxError as err: |
| 733 | error(err, filename) |
Andrew Svetlov | f7a17b4 | 2012-12-25 16:47:37 +0200 | [diff] [blame] | 734 | except OSError as err: |
Meador Inge | 14c0f03 | 2011-10-07 08:53:38 -0500 | [diff] [blame] | 735 | error(err) |
| 736 | except KeyboardInterrupt: |
| 737 | print("interrupted\n") |
| 738 | except Exception as err: |
| 739 | perror("unexpected error: %s" % err) |
| 740 | raise |
| 741 | |
Raymond Hettinger | 6c60d09 | 2010-09-09 04:32:39 +0000 | [diff] [blame] | 742 | if __name__ == "__main__": |
Meador Inge | 14c0f03 | 2011-10-07 08:53:38 -0500 | [diff] [blame] | 743 | main() |