Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/AnonR/smanonr..../lib64/python3....
File: tokenize.py
"""Tokenization help for Python programs.
[0] Fix | Delete
[1] Fix | Delete
tokenize(readline) is a generator that breaks a stream of bytes into
[2] Fix | Delete
Python tokens. It decodes the bytes according to PEP-0263 for
[3] Fix | Delete
determining source file encoding.
[4] Fix | Delete
[5] Fix | Delete
It accepts a readline-like method which is called repeatedly to get the
[6] Fix | Delete
next line of input (or b"" for EOF). It generates 5-tuples with these
[7] Fix | Delete
members:
[8] Fix | Delete
[9] Fix | Delete
the token type (see token.py)
[10] Fix | Delete
the token (a string)
[11] Fix | Delete
the starting (row, column) indices of the token (a 2-tuple of ints)
[12] Fix | Delete
the ending (row, column) indices of the token (a 2-tuple of ints)
[13] Fix | Delete
the original line (string)
[14] Fix | Delete
[15] Fix | Delete
It is designed to match the working of the Python tokenizer exactly, except
[16] Fix | Delete
that it produces COMMENT tokens for comments and gives type OP for all
[17] Fix | Delete
operators. Additionally, all token lists start with an ENCODING token
[18] Fix | Delete
which tells you which encoding was used to decode the bytes stream.
[19] Fix | Delete
"""
[20] Fix | Delete
[21] Fix | Delete
__author__ = 'Ka-Ping Yee <ping@lfw.org>'
[22] Fix | Delete
__credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
[23] Fix | Delete
'Skip Montanaro, Raymond Hettinger, Trent Nelson, '
[24] Fix | Delete
'Michael Foord')
[25] Fix | Delete
from builtins import open as _builtin_open
[26] Fix | Delete
from codecs import lookup, BOM_UTF8
[27] Fix | Delete
import collections
[28] Fix | Delete
from io import TextIOWrapper
[29] Fix | Delete
import itertools as _itertools
[30] Fix | Delete
import re
[31] Fix | Delete
import sys
[32] Fix | Delete
from token import *
[33] Fix | Delete
from token import EXACT_TOKEN_TYPES
[34] Fix | Delete
[35] Fix | Delete
cookie_re = re.compile(r'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII)
[36] Fix | Delete
blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII)
[37] Fix | Delete
[38] Fix | Delete
import token
[39] Fix | Delete
__all__ = token.__all__ + ["tokenize", "generate_tokens", "detect_encoding",
[40] Fix | Delete
"untokenize", "TokenInfo"]
[41] Fix | Delete
del token
[42] Fix | Delete
[43] Fix | Delete
class TokenInfo(collections.namedtuple('TokenInfo', 'type string start end line')):
[44] Fix | Delete
def __repr__(self):
[45] Fix | Delete
annotated_type = '%d (%s)' % (self.type, tok_name[self.type])
[46] Fix | Delete
return ('TokenInfo(type=%s, string=%r, start=%r, end=%r, line=%r)' %
[47] Fix | Delete
self._replace(type=annotated_type))
[48] Fix | Delete
[49] Fix | Delete
@property
[50] Fix | Delete
def exact_type(self):
[51] Fix | Delete
if self.type == OP and self.string in EXACT_TOKEN_TYPES:
[52] Fix | Delete
return EXACT_TOKEN_TYPES[self.string]
[53] Fix | Delete
else:
[54] Fix | Delete
return self.type
[55] Fix | Delete
[56] Fix | Delete
def group(*choices): return '(' + '|'.join(choices) + ')'
[57] Fix | Delete
def any(*choices): return group(*choices) + '*'
[58] Fix | Delete
def maybe(*choices): return group(*choices) + '?'
[59] Fix | Delete
[60] Fix | Delete
# Note: we use unicode matching for names ("\w") but ascii matching for
[61] Fix | Delete
# number literals.
[62] Fix | Delete
Whitespace = r'[ \f\t]*'
[63] Fix | Delete
Comment = r'#[^\r\n]*'
[64] Fix | Delete
Ignore = Whitespace + any(r'\\\r?\n' + Whitespace) + maybe(Comment)
[65] Fix | Delete
Name = r'\w+'
[66] Fix | Delete
[67] Fix | Delete
Hexnumber = r'0[xX](?:_?[0-9a-fA-F])+'
[68] Fix | Delete
Binnumber = r'0[bB](?:_?[01])+'
[69] Fix | Delete
Octnumber = r'0[oO](?:_?[0-7])+'
[70] Fix | Delete
Decnumber = r'(?:0(?:_?0)*|[1-9](?:_?[0-9])*)'
[71] Fix | Delete
Intnumber = group(Hexnumber, Binnumber, Octnumber, Decnumber)
[72] Fix | Delete
Exponent = r'[eE][-+]?[0-9](?:_?[0-9])*'
[73] Fix | Delete
Pointfloat = group(r'[0-9](?:_?[0-9])*\.(?:[0-9](?:_?[0-9])*)?',
[74] Fix | Delete
r'\.[0-9](?:_?[0-9])*') + maybe(Exponent)
[75] Fix | Delete
Expfloat = r'[0-9](?:_?[0-9])*' + Exponent
[76] Fix | Delete
Floatnumber = group(Pointfloat, Expfloat)
[77] Fix | Delete
Imagnumber = group(r'[0-9](?:_?[0-9])*[jJ]', Floatnumber + r'[jJ]')
[78] Fix | Delete
Number = group(Imagnumber, Floatnumber, Intnumber)
[79] Fix | Delete
[80] Fix | Delete
# Return the empty string, plus all of the valid string prefixes.
[81] Fix | Delete
def _all_string_prefixes():
[82] Fix | Delete
# The valid string prefixes. Only contain the lower case versions,
[83] Fix | Delete
# and don't contain any permutations (include 'fr', but not
[84] Fix | Delete
# 'rf'). The various permutations will be generated.
[85] Fix | Delete
_valid_string_prefixes = ['b', 'r', 'u', 'f', 'br', 'fr']
[86] Fix | Delete
# if we add binary f-strings, add: ['fb', 'fbr']
[87] Fix | Delete
result = {''}
[88] Fix | Delete
for prefix in _valid_string_prefixes:
[89] Fix | Delete
for t in _itertools.permutations(prefix):
[90] Fix | Delete
# create a list with upper and lower versions of each
[91] Fix | Delete
# character
[92] Fix | Delete
for u in _itertools.product(*[(c, c.upper()) for c in t]):
[93] Fix | Delete
result.add(''.join(u))
[94] Fix | Delete
return result
[95] Fix | Delete
[96] Fix | Delete
def _compile(expr):
[97] Fix | Delete
return re.compile(expr, re.UNICODE)
[98] Fix | Delete
[99] Fix | Delete
# Note that since _all_string_prefixes includes the empty string,
[100] Fix | Delete
# StringPrefix can be the empty string (making it optional).
[101] Fix | Delete
StringPrefix = group(*_all_string_prefixes())
[102] Fix | Delete
[103] Fix | Delete
# Tail end of ' string.
[104] Fix | Delete
Single = r"[^'\\]*(?:\\.[^'\\]*)*'"
[105] Fix | Delete
# Tail end of " string.
[106] Fix | Delete
Double = r'[^"\\]*(?:\\.[^"\\]*)*"'
[107] Fix | Delete
# Tail end of ''' string.
[108] Fix | Delete
Single3 = r"[^'\\]*(?:(?:\\.|'(?!''))[^'\\]*)*'''"
[109] Fix | Delete
# Tail end of """ string.
[110] Fix | Delete
Double3 = r'[^"\\]*(?:(?:\\.|"(?!""))[^"\\]*)*"""'
[111] Fix | Delete
Triple = group(StringPrefix + "'''", StringPrefix + '"""')
[112] Fix | Delete
# Single-line ' or " string.
[113] Fix | Delete
String = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*'",
[114] Fix | Delete
StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*"')
[115] Fix | Delete
[116] Fix | Delete
# Sorting in reverse order puts the long operators before their prefixes.
[117] Fix | Delete
# Otherwise if = came before ==, == would get recognized as two instances
[118] Fix | Delete
# of =.
[119] Fix | Delete
Special = group(*map(re.escape, sorted(EXACT_TOKEN_TYPES, reverse=True)))
[120] Fix | Delete
Funny = group(r'\r?\n', Special)
[121] Fix | Delete
[122] Fix | Delete
PlainToken = group(Number, Funny, String, Name)
[123] Fix | Delete
Token = Ignore + PlainToken
[124] Fix | Delete
[125] Fix | Delete
# First (or only) line of ' or " string.
[126] Fix | Delete
ContStr = group(StringPrefix + r"'[^\n'\\]*(?:\\.[^\n'\\]*)*" +
[127] Fix | Delete
group("'", r'\\\r?\n'),
[128] Fix | Delete
StringPrefix + r'"[^\n"\\]*(?:\\.[^\n"\\]*)*' +
[129] Fix | Delete
group('"', r'\\\r?\n'))
[130] Fix | Delete
PseudoExtras = group(r'\\\r?\n|\Z', Comment, Triple)
[131] Fix | Delete
PseudoToken = Whitespace + group(PseudoExtras, Number, Funny, ContStr, Name)
[132] Fix | Delete
[133] Fix | Delete
# For a given string prefix plus quotes, endpats maps it to a regex
[134] Fix | Delete
# to match the remainder of that string. _prefix can be empty, for
[135] Fix | Delete
# a normal single or triple quoted string (with no prefix).
[136] Fix | Delete
endpats = {}
[137] Fix | Delete
for _prefix in _all_string_prefixes():
[138] Fix | Delete
endpats[_prefix + "'"] = Single
[139] Fix | Delete
endpats[_prefix + '"'] = Double
[140] Fix | Delete
endpats[_prefix + "'''"] = Single3
[141] Fix | Delete
endpats[_prefix + '"""'] = Double3
[142] Fix | Delete
[143] Fix | Delete
# A set of all of the single and triple quoted string prefixes,
[144] Fix | Delete
# including the opening quotes.
[145] Fix | Delete
single_quoted = set()
[146] Fix | Delete
triple_quoted = set()
[147] Fix | Delete
for t in _all_string_prefixes():
[148] Fix | Delete
for u in (t + '"', t + "'"):
[149] Fix | Delete
single_quoted.add(u)
[150] Fix | Delete
for u in (t + '"""', t + "'''"):
[151] Fix | Delete
triple_quoted.add(u)
[152] Fix | Delete
[153] Fix | Delete
tabsize = 8
[154] Fix | Delete
[155] Fix | Delete
class TokenError(Exception): pass
[156] Fix | Delete
[157] Fix | Delete
class StopTokenizing(Exception): pass
[158] Fix | Delete
[159] Fix | Delete
[160] Fix | Delete
class Untokenizer:
[161] Fix | Delete
[162] Fix | Delete
def __init__(self):
[163] Fix | Delete
self.tokens = []
[164] Fix | Delete
self.prev_row = 1
[165] Fix | Delete
self.prev_col = 0
[166] Fix | Delete
self.encoding = None
[167] Fix | Delete
[168] Fix | Delete
def add_whitespace(self, start):
[169] Fix | Delete
row, col = start
[170] Fix | Delete
if row < self.prev_row or row == self.prev_row and col < self.prev_col:
[171] Fix | Delete
raise ValueError("start ({},{}) precedes previous end ({},{})"
[172] Fix | Delete
.format(row, col, self.prev_row, self.prev_col))
[173] Fix | Delete
row_offset = row - self.prev_row
[174] Fix | Delete
if row_offset:
[175] Fix | Delete
self.tokens.append("\\\n" * row_offset)
[176] Fix | Delete
self.prev_col = 0
[177] Fix | Delete
col_offset = col - self.prev_col
[178] Fix | Delete
if col_offset:
[179] Fix | Delete
self.tokens.append(" " * col_offset)
[180] Fix | Delete
[181] Fix | Delete
def untokenize(self, iterable):
[182] Fix | Delete
it = iter(iterable)
[183] Fix | Delete
indents = []
[184] Fix | Delete
startline = False
[185] Fix | Delete
for t in it:
[186] Fix | Delete
if len(t) == 2:
[187] Fix | Delete
self.compat(t, it)
[188] Fix | Delete
break
[189] Fix | Delete
tok_type, token, start, end, line = t
[190] Fix | Delete
if tok_type == ENCODING:
[191] Fix | Delete
self.encoding = token
[192] Fix | Delete
continue
[193] Fix | Delete
if tok_type == ENDMARKER:
[194] Fix | Delete
break
[195] Fix | Delete
if tok_type == INDENT:
[196] Fix | Delete
indents.append(token)
[197] Fix | Delete
continue
[198] Fix | Delete
elif tok_type == DEDENT:
[199] Fix | Delete
indents.pop()
[200] Fix | Delete
self.prev_row, self.prev_col = end
[201] Fix | Delete
continue
[202] Fix | Delete
elif tok_type in (NEWLINE, NL):
[203] Fix | Delete
startline = True
[204] Fix | Delete
elif startline and indents:
[205] Fix | Delete
indent = indents[-1]
[206] Fix | Delete
if start[1] >= len(indent):
[207] Fix | Delete
self.tokens.append(indent)
[208] Fix | Delete
self.prev_col = len(indent)
[209] Fix | Delete
startline = False
[210] Fix | Delete
self.add_whitespace(start)
[211] Fix | Delete
self.tokens.append(token)
[212] Fix | Delete
self.prev_row, self.prev_col = end
[213] Fix | Delete
if tok_type in (NEWLINE, NL):
[214] Fix | Delete
self.prev_row += 1
[215] Fix | Delete
self.prev_col = 0
[216] Fix | Delete
return "".join(self.tokens)
[217] Fix | Delete
[218] Fix | Delete
def compat(self, token, iterable):
[219] Fix | Delete
indents = []
[220] Fix | Delete
toks_append = self.tokens.append
[221] Fix | Delete
startline = token[0] in (NEWLINE, NL)
[222] Fix | Delete
prevstring = False
[223] Fix | Delete
[224] Fix | Delete
for tok in _itertools.chain([token], iterable):
[225] Fix | Delete
toknum, tokval = tok[:2]
[226] Fix | Delete
if toknum == ENCODING:
[227] Fix | Delete
self.encoding = tokval
[228] Fix | Delete
continue
[229] Fix | Delete
[230] Fix | Delete
if toknum in (NAME, NUMBER):
[231] Fix | Delete
tokval += ' '
[232] Fix | Delete
[233] Fix | Delete
# Insert a space between two consecutive strings
[234] Fix | Delete
if toknum == STRING:
[235] Fix | Delete
if prevstring:
[236] Fix | Delete
tokval = ' ' + tokval
[237] Fix | Delete
prevstring = True
[238] Fix | Delete
else:
[239] Fix | Delete
prevstring = False
[240] Fix | Delete
[241] Fix | Delete
if toknum == INDENT:
[242] Fix | Delete
indents.append(tokval)
[243] Fix | Delete
continue
[244] Fix | Delete
elif toknum == DEDENT:
[245] Fix | Delete
indents.pop()
[246] Fix | Delete
continue
[247] Fix | Delete
elif toknum in (NEWLINE, NL):
[248] Fix | Delete
startline = True
[249] Fix | Delete
elif startline and indents:
[250] Fix | Delete
toks_append(indents[-1])
[251] Fix | Delete
startline = False
[252] Fix | Delete
toks_append(tokval)
[253] Fix | Delete
[254] Fix | Delete
[255] Fix | Delete
def untokenize(iterable):
[256] Fix | Delete
"""Transform tokens back into Python source code.
[257] Fix | Delete
It returns a bytes object, encoded using the ENCODING
[258] Fix | Delete
token, which is the first token sequence output by tokenize.
[259] Fix | Delete
[260] Fix | Delete
Each element returned by the iterable must be a token sequence
[261] Fix | Delete
with at least two elements, a token number and token value. If
[262] Fix | Delete
only two tokens are passed, the resulting output is poor.
[263] Fix | Delete
[264] Fix | Delete
Round-trip invariant for full input:
[265] Fix | Delete
Untokenized source will match input source exactly
[266] Fix | Delete
[267] Fix | Delete
Round-trip invariant for limited input:
[268] Fix | Delete
# Output bytes will tokenize back to the input
[269] Fix | Delete
t1 = [tok[:2] for tok in tokenize(f.readline)]
[270] Fix | Delete
newcode = untokenize(t1)
[271] Fix | Delete
readline = BytesIO(newcode).readline
[272] Fix | Delete
t2 = [tok[:2] for tok in tokenize(readline)]
[273] Fix | Delete
assert t1 == t2
[274] Fix | Delete
"""
[275] Fix | Delete
ut = Untokenizer()
[276] Fix | Delete
out = ut.untokenize(iterable)
[277] Fix | Delete
if ut.encoding is not None:
[278] Fix | Delete
out = out.encode(ut.encoding)
[279] Fix | Delete
return out
[280] Fix | Delete
[281] Fix | Delete
[282] Fix | Delete
def _get_normal_name(orig_enc):
[283] Fix | Delete
"""Imitates get_normal_name in tokenizer.c."""
[284] Fix | Delete
# Only care about the first 12 characters.
[285] Fix | Delete
enc = orig_enc[:12].lower().replace("_", "-")
[286] Fix | Delete
if enc == "utf-8" or enc.startswith("utf-8-"):
[287] Fix | Delete
return "utf-8"
[288] Fix | Delete
if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
[289] Fix | Delete
enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
[290] Fix | Delete
return "iso-8859-1"
[291] Fix | Delete
return orig_enc
[292] Fix | Delete
[293] Fix | Delete
def detect_encoding(readline):
[294] Fix | Delete
"""
[295] Fix | Delete
The detect_encoding() function is used to detect the encoding that should
[296] Fix | Delete
be used to decode a Python source file. It requires one argument, readline,
[297] Fix | Delete
in the same way as the tokenize() generator.
[298] Fix | Delete
[299] Fix | Delete
It will call readline a maximum of twice, and return the encoding used
[300] Fix | Delete
(as a string) and a list of any lines (left as bytes) it has read in.
[301] Fix | Delete
[302] Fix | Delete
It detects the encoding from the presence of a utf-8 bom or an encoding
[303] Fix | Delete
cookie as specified in pep-0263. If both a bom and a cookie are present,
[304] Fix | Delete
but disagree, a SyntaxError will be raised. If the encoding cookie is an
[305] Fix | Delete
invalid charset, raise a SyntaxError. Note that if a utf-8 bom is found,
[306] Fix | Delete
'utf-8-sig' is returned.
[307] Fix | Delete
[308] Fix | Delete
If no encoding is specified, then the default of 'utf-8' will be returned.
[309] Fix | Delete
"""
[310] Fix | Delete
try:
[311] Fix | Delete
filename = readline.__self__.name
[312] Fix | Delete
except AttributeError:
[313] Fix | Delete
filename = None
[314] Fix | Delete
bom_found = False
[315] Fix | Delete
encoding = None
[316] Fix | Delete
default = 'utf-8'
[317] Fix | Delete
def read_or_stop():
[318] Fix | Delete
try:
[319] Fix | Delete
return readline()
[320] Fix | Delete
except StopIteration:
[321] Fix | Delete
return b''
[322] Fix | Delete
[323] Fix | Delete
def find_cookie(line):
[324] Fix | Delete
try:
[325] Fix | Delete
# Decode as UTF-8. Either the line is an encoding declaration,
[326] Fix | Delete
# in which case it should be pure ASCII, or it must be UTF-8
[327] Fix | Delete
# per default encoding.
[328] Fix | Delete
line_string = line.decode('utf-8')
[329] Fix | Delete
except UnicodeDecodeError:
[330] Fix | Delete
msg = "invalid or missing encoding declaration"
[331] Fix | Delete
if filename is not None:
[332] Fix | Delete
msg = '{} for {!r}'.format(msg, filename)
[333] Fix | Delete
raise SyntaxError(msg)
[334] Fix | Delete
[335] Fix | Delete
match = cookie_re.match(line_string)
[336] Fix | Delete
if not match:
[337] Fix | Delete
return None
[338] Fix | Delete
encoding = _get_normal_name(match.group(1))
[339] Fix | Delete
try:
[340] Fix | Delete
codec = lookup(encoding)
[341] Fix | Delete
except LookupError:
[342] Fix | Delete
# This behaviour mimics the Python interpreter
[343] Fix | Delete
if filename is None:
[344] Fix | Delete
msg = "unknown encoding: " + encoding
[345] Fix | Delete
else:
[346] Fix | Delete
msg = "unknown encoding for {!r}: {}".format(filename,
[347] Fix | Delete
encoding)
[348] Fix | Delete
raise SyntaxError(msg)
[349] Fix | Delete
[350] Fix | Delete
if bom_found:
[351] Fix | Delete
if encoding != 'utf-8':
[352] Fix | Delete
# This behaviour mimics the Python interpreter
[353] Fix | Delete
if filename is None:
[354] Fix | Delete
msg = 'encoding problem: utf-8'
[355] Fix | Delete
else:
[356] Fix | Delete
msg = 'encoding problem for {!r}: utf-8'.format(filename)
[357] Fix | Delete
raise SyntaxError(msg)
[358] Fix | Delete
encoding += '-sig'
[359] Fix | Delete
return encoding
[360] Fix | Delete
[361] Fix | Delete
first = read_or_stop()
[362] Fix | Delete
if first.startswith(BOM_UTF8):
[363] Fix | Delete
bom_found = True
[364] Fix | Delete
first = first[3:]
[365] Fix | Delete
default = 'utf-8-sig'
[366] Fix | Delete
if not first:
[367] Fix | Delete
return default, []
[368] Fix | Delete
[369] Fix | Delete
encoding = find_cookie(first)
[370] Fix | Delete
if encoding:
[371] Fix | Delete
return encoding, [first]
[372] Fix | Delete
if not blank_re.match(first):
[373] Fix | Delete
return default, [first]
[374] Fix | Delete
[375] Fix | Delete
second = read_or_stop()
[376] Fix | Delete
if not second:
[377] Fix | Delete
return default, [first]
[378] Fix | Delete
[379] Fix | Delete
encoding = find_cookie(second)
[380] Fix | Delete
if encoding:
[381] Fix | Delete
return encoding, [first, second]
[382] Fix | Delete
[383] Fix | Delete
return default, [first, second]
[384] Fix | Delete
[385] Fix | Delete
[386] Fix | Delete
def open(filename):
[387] Fix | Delete
"""Open a file in read only mode using the encoding detected by
[388] Fix | Delete
detect_encoding().
[389] Fix | Delete
"""
[390] Fix | Delete
buffer = _builtin_open(filename, 'rb')
[391] Fix | Delete
try:
[392] Fix | Delete
encoding, lines = detect_encoding(buffer.readline)
[393] Fix | Delete
buffer.seek(0)
[394] Fix | Delete
text = TextIOWrapper(buffer, encoding, line_buffering=True)
[395] Fix | Delete
text.mode = 'r'
[396] Fix | Delete
return text
[397] Fix | Delete
except:
[398] Fix | Delete
buffer.close()
[399] Fix | Delete
raise
[400] Fix | Delete
[401] Fix | Delete
[402] Fix | Delete
def tokenize(readline):
[403] Fix | Delete
"""
[404] Fix | Delete
The tokenize() generator requires one argument, readline, which
[405] Fix | Delete
must be a callable object which provides the same interface as the
[406] Fix | Delete
readline() method of built-in file objects. Each call to the function
[407] Fix | Delete
should return one line of input as bytes. Alternatively, readline
[408] Fix | Delete
can be a callable function terminating with StopIteration:
[409] Fix | Delete
readline = open(myfile, 'rb').__next__ # Example of alternate readline
[410] Fix | Delete
[411] Fix | Delete
The generator produces 5-tuples with these members: the token type; the
[412] Fix | Delete
token string; a 2-tuple (srow, scol) of ints specifying the row and
[413] Fix | Delete
column where the token begins in the source; a 2-tuple (erow, ecol) of
[414] Fix | Delete
ints specifying the row and column where the token ends in the source;
[415] Fix | Delete
and the line on which the token was found. The line passed is the
[416] Fix | Delete
physical line.
[417] Fix | Delete
[418] Fix | Delete
The first token sequence will always be an ENCODING token
[419] Fix | Delete
which tells you which encoding was used to decode the bytes stream.
[420] Fix | Delete
"""
[421] Fix | Delete
encoding, consumed = detect_encoding(readline)
[422] Fix | Delete
empty = _itertools.repeat(b"")
[423] Fix | Delete
rl_gen = _itertools.chain(consumed, iter(readline, b""), empty)
[424] Fix | Delete
return _tokenize(rl_gen.__next__, encoding)
[425] Fix | Delete
[426] Fix | Delete
[427] Fix | Delete
def _tokenize(readline, encoding):
[428] Fix | Delete
lnum = parenlev = continued = 0
[429] Fix | Delete
numchars = '0123456789'
[430] Fix | Delete
contstr, needcont = '', 0
[431] Fix | Delete
contline = None
[432] Fix | Delete
indents = [0]
[433] Fix | Delete
[434] Fix | Delete
if encoding is not None:
[435] Fix | Delete
if encoding == "utf-8-sig":
[436] Fix | Delete
# BOM will already have been stripped.
[437] Fix | Delete
encoding = "utf-8"
[438] Fix | Delete
yield TokenInfo(ENCODING, encoding, (0, 0), (0, 0), '')
[439] Fix | Delete
last_line = b''
[440] Fix | Delete
line = b''
[441] Fix | Delete
while True: # loop over lines in stream
[442] Fix | Delete
try:
[443] Fix | Delete
# We capture the value of the line variable here because
[444] Fix | Delete
# readline uses the empty string '' to signal end of input,
[445] Fix | Delete
# hence `line` itself will always be overwritten at the end
[446] Fix | Delete
# of this loop.
[447] Fix | Delete
last_line = line
[448] Fix | Delete
line = readline()
[449] Fix | Delete
except StopIteration:
[450] Fix | Delete
line = b''
[451] Fix | Delete
[452] Fix | Delete
if encoding is not None:
[453] Fix | Delete
line = line.decode(encoding)
[454] Fix | Delete
lnum += 1
[455] Fix | Delete
pos, max = 0, len(line)
[456] Fix | Delete
[457] Fix | Delete
if contstr: # continued string
[458] Fix | Delete
if not line:
[459] Fix | Delete
raise TokenError("EOF in multi-line string", strstart)
[460] Fix | Delete
endmatch = endprog.match(line)
[461] Fix | Delete
if endmatch:
[462] Fix | Delete
pos = end = endmatch.end(0)
[463] Fix | Delete
yield TokenInfo(STRING, contstr + line[:end],
[464] Fix | Delete
strstart, (lnum, end), contline + line)
[465] Fix | Delete
contstr, needcont = '', 0
[466] Fix | Delete
contline = None
[467] Fix | Delete
elif needcont and line[-2:] != '\\\n' and line[-3:] != '\\\r\n':
[468] Fix | Delete
yield TokenInfo(ERRORTOKEN, contstr + line,
[469] Fix | Delete
strstart, (lnum, len(line)), contline)
[470] Fix | Delete
contstr = ''
[471] Fix | Delete
contline = None
[472] Fix | Delete
continue
[473] Fix | Delete
else:
[474] Fix | Delete
contstr = contstr + line
[475] Fix | Delete
contline = contline + line
[476] Fix | Delete
continue
[477] Fix | Delete
[478] Fix | Delete
elif parenlev == 0 and not continued: # new statement
[479] Fix | Delete
if not line: break
[480] Fix | Delete
column = 0
[481] Fix | Delete
while pos < max: # measure leading whitespace
[482] Fix | Delete
if line[pos] == ' ':
[483] Fix | Delete
column += 1
[484] Fix | Delete
elif line[pos] == '\t':
[485] Fix | Delete
column = (column//tabsize + 1)*tabsize
[486] Fix | Delete
elif line[pos] == '\f':
[487] Fix | Delete
column = 0
[488] Fix | Delete
else:
[489] Fix | Delete
break
[490] Fix | Delete
pos += 1
[491] Fix | Delete
if pos == max:
[492] Fix | Delete
break
[493] Fix | Delete
[494] Fix | Delete
if line[pos] in '#\r\n': # skip comments or blank lines
[495] Fix | Delete
if line[pos] == '#':
[496] Fix | Delete
comment_token = line[pos:].rstrip('\r\n')
[497] Fix | Delete
yield TokenInfo(COMMENT, comment_token,
[498] Fix | Delete
(lnum, pos), (lnum, pos + len(comment_token)), line)
[499] Fix | Delete
12
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function