| 1 |
"""A collection of useful functions and methods to deal with tokenizing |
| 2 |
source code. |
| 3 |
""" |
| 4 |
# Starting with Python 3.12, the tokenizer was completely rewritten to handle more general |
| 5 |
# f-strings. The following warning was added to the documentation: |
| 6 |
# |
| 7 |
# Warning Note that the functions in this module are only designed to parse |
| 8 |
# syntactically valid Python code (code that does not raise when parsed using ast.parse()). |
| 9 |
# The behavior of the functions in this module is undefined when providing invalid Python code |
| 10 |
# and it can change at any point. |
| 11 |
# |
| 12 |
# In order to provide more precise help when user code contains SyntaxErrors, we are left |
| 13 |
# to deal in an ad-hoc manner to retrieve some invalid tokens. |
| 14 |
# |
| 15 |
|
| 16 |
import ast |
| 17 |
import keyword |
| 18 |
import sys |
| 19 |
import tokenize as py_tokenize |
| 20 |
from io import StringIO |
| 21 |
from typing import Any, Iterable, List, Sequence, Tuple, Union |
| 22 |
|
| 23 |
from . import debug_helper |
| 24 |
|
| 25 |
_TokenInfo = Union[ |
| 26 |
py_tokenize.TokenInfo, Tuple[int, str, Tuple[int, int], Tuple[int, int], str] |
| 27 |
] |
| 28 |
|
| 29 |
_token_format = "type={type} string={string} start={start} end={end} line={line}" |
| 30 |
|
| 31 |
UNCLOSED = -9 |
| 32 |
assert UNCLOSED not in py_tokenize.tok_name |
| 33 |
py_tokenize.tok_name[UNCLOSED] = "UNCLOSED_STRING" |
| 34 |
|
| 35 |
|
| 36 |
class Token: |
| 37 |
"""Token as generated from Python's tokenize.generate_tokens written here in |
| 38 |
a more convenient form, and with some custom methods. |
| 39 |
|
| 40 |
The various parameters are:: |
| 41 |
|
| 42 |
type: token type |
| 43 |
string: the token written as a string |
| 44 |
start = (start_row, start_col) |
| 45 |
end = (end_row, end_col) |
| 46 |
line: entire line of code where the token is found. |
| 47 |
|
| 48 |
Token instances are mutable objects. Therefore, given a list of tokens, |
| 49 |
we can change the value of any token's attribute, untokenize the list and |
| 50 |
automatically obtain a transformed source. Almost always, the attribute |
| 51 |
to be transformed will be the string attribute. |
| 52 |
""" |
| 53 |
|
| 54 |
def __init__(self, token: _TokenInfo) -> None: |
| 55 |
self.type = token[0] |
| 56 |
self.string = token[1] |
| 57 |
self.start = self.start_row, self.start_col = token[2] |
| 58 |
self.end = self.end_row, self.end_col = token[3] |
| 59 |
self.line = token[4] |
| 60 |
|
| 61 |
def copy(self) -> "Token": |
| 62 |
"""Makes a copy of a given token""" |
| 63 |
return Token((self.type, self.string, self.start, self.end, self.line)) |
| 64 |
|
| 65 |
def __eq__(self, other: object) -> bool: |
| 66 |
"""Compares a Token with another object; returns true if |
| 67 |
self.string == other.string or if self.string == other. |
| 68 |
""" |
| 69 |
return self.string == str(other) |
| 70 |
|
| 71 |
def __repr__(self) -> str: # pragma: no cover |
| 72 |
"""Nicely formatted token to help with debugging session. |
| 73 |
|
| 74 |
Note that it does **not** print a string representation that could be |
| 75 |
used to create a new ``Token`` instance, which is something you should |
| 76 |
never need to do other than indirectly by using the functions |
| 77 |
provided in this module. |
| 78 |
""" |
| 79 |
return _token_format.format( |
| 80 |
type="%s (%s)" % (self.type, py_tokenize.tok_name[self.type]), |
| 81 |
string=repr(self.string), |
| 82 |
start=str(self.start), |
| 83 |
end=str(self.end), |
| 84 |
line=repr(self.line), |
| 85 |
) |
| 86 |
|
| 87 |
def __str__(self) -> str: |
| 88 |
"""Returns the string attribute.""" |
| 89 |
return self.string |
| 90 |
|
| 91 |
def __len__(self): |
| 92 |
"""Returns the length of the string attribute""" |
| 93 |
return len(self.string) |
| 94 |
|
| 95 |
def is_comment(self) -> bool: |
| 96 |
"""Returns True if the token is a comment.""" |
| 97 |
return self.type == py_tokenize.COMMENT |
| 98 |
|
| 99 |
def is_identifier(self) -> bool: |
| 100 |
"""Returns ``True`` if the token represents a valid Python identifier |
| 101 |
excluding Python keywords. |
| 102 |
|
| 103 |
Note: this is different from Python's string method ``isidentifier`` |
| 104 |
which also returns ``True`` if the string is a keyword. |
| 105 |
""" |
| 106 |
return self.string.isidentifier() and not self.is_keyword() |
| 107 |
|
| 108 |
def is_name(self) -> bool: |
| 109 |
"""Returns ``True`` if the token is a type NAME""" |
| 110 |
return self.type == py_tokenize.NAME |
| 111 |
|
| 112 |
def is_keyword(self) -> bool: |
| 113 |
"""Returns True if the token represents a Python keyword.""" |
| 114 |
return keyword.iskeyword(self.string) or self.string in ["__debug__", "..."] |
| 115 |
|
| 116 |
def is_number(self) -> bool: |
| 117 |
"""Returns True if the token represents a number of any type""" |
| 118 |
return self.type == py_tokenize.NUMBER |
| 119 |
|
| 120 |
def is_operator(self) -> bool: |
| 121 |
"""Returns true if the token is of type OP""" |
| 122 |
return self.type == py_tokenize.OP |
| 123 |
|
| 124 |
def is_float(self) -> bool: |
| 125 |
"""Returns True if the token represents a float""" |
| 126 |
return self.is_number() and isinstance(ast.literal_eval(self.string), float) |
| 127 |
|
| 128 |
def is_integer(self) -> bool: |
| 129 |
"""Returns True if the token represents an integer""" |
| 130 |
return self.is_number() and isinstance(ast.literal_eval(self.string), int) |
| 131 |
|
| 132 |
def is_complex(self) -> bool: |
| 133 |
"""Returns True if the token represents a complex number""" |
| 134 |
return self.is_number() and isinstance(ast.literal_eval(self.string), complex) |
| 135 |
|
| 136 |
def is_space(self) -> bool: |
| 137 |
"""Returns True if the token indicates a change in indentation, |
| 138 |
the end of a line, or the end of the source |
| 139 |
(``INDENT``, ``DEDENT``, ``NEWLINE``, ``NL``, and ``ENDMARKER``). |
| 140 |
|
| 141 |
Note that spaces, including tab characters ``\\t``, between tokens |
| 142 |
on a given line are not considered to be tokens themselves. |
| 143 |
""" |
| 144 |
return self.type in ( |
| 145 |
py_tokenize.INDENT, |
| 146 |
py_tokenize.DEDENT, |
| 147 |
py_tokenize.NEWLINE, |
| 148 |
py_tokenize.NL, |
| 149 |
py_tokenize.ENDMARKER, |
| 150 |
) |
| 151 |
|
| 152 |
def is_string(self) -> bool: |
| 153 |
"""Returns True if the token is a string""" |
| 154 |
return self.type == py_tokenize.STRING |
| 155 |
|
| 156 |
def is_f_string(self) -> bool: |
| 157 |
"""Return True if the token is an f-string""" |
| 158 |
return self.type == py_tokenize.STRING and ( |
| 159 |
self.string.startswith("f") or self.string.startswith("F") |
| 160 |
) |
| 161 |
|
| 162 |
def is_unclosed_string(self) -> bool: |
| 163 |
"""Returns True if the token is part of an unclosed triple-quoted string""" |
| 164 |
return self.type == UNCLOSED |
| 165 |
|
| 166 |
def immediately_before(self, other: Any) -> bool: |
| 167 |
"""Returns True if the current token is immediately before other, |
| 168 |
without any intervening space in between the two tokens. |
| 169 |
""" |
| 170 |
if not isinstance(other, Token): # pragma: no cover |
| 171 |
return False |
| 172 |
return self.end_row == other.start_row and self.end_col == other.start_col |
| 173 |
|
| 174 |
def immediately_after(self, other: Any) -> bool: |
| 175 |
"""Returns True if the current token is immediately after other, |
| 176 |
without any intervening space in between the two tokens. |
| 177 |
""" |
| 178 |
if not isinstance(other, Token): # pragma: no cover |
| 179 |
return False |
| 180 |
return other.immediately_before(self) |
| 181 |
|
| 182 |
def is_error(self) -> bool: |
| 183 |
"""Returns True if the current token is an error token""" |
| 184 |
return self.type == py_tokenize.ERRORTOKEN |
| 185 |
|
| 186 |
def name(self) -> str: |
| 187 |
"""Returns the name of the character type""" |
| 188 |
return py_tokenize.tok_name[self.type] |
| 189 |
|
| 190 |
|
| 191 |
def is_assignment(op: Union[str, Token]) -> bool: |
| 192 |
"""Returns True if op (string or Token) is an assigment or augmented assignment.""" |
| 193 |
ops = [ |
| 194 |
"=", |
| 195 |
"+=", |
| 196 |
"-=", |
| 197 |
"*=", |
| 198 |
"@=", |
| 199 |
"/=", |
| 200 |
"//=", |
| 201 |
"%=", |
| 202 |
"**=", |
| 203 |
">>=", |
| 204 |
"<<=", |
| 205 |
"&=", |
| 206 |
"^=", |
| 207 |
"|=", |
| 208 |
] |
| 209 |
if sys.version_info >= (3, 8): |
| 210 |
ops.append(":=") |
| 211 |
return str(op) in ops |
| 212 |
|
| 213 |
|
| 214 |
def is_bitwise(op: Union[str, Token]) -> bool: |
| 215 |
"""Returns True if op (string or Token) is a bitwise operator.""" |
| 216 |
ops = ["^", "&", "|", "<<", ">>", "~"] |
| 217 |
return str(op) in ops |
| 218 |
|
| 219 |
|
| 220 |
def is_comparison(op: Union[str, Token]) -> bool: |
| 221 |
"""Returns True if op (string or Token) is a comparison operator.""" |
| 222 |
ops = ["<", ">", "<=", ">=", "==", "!="] |
| 223 |
return str(op) in ops |
| 224 |
|
| 225 |
|
| 226 |
def is_math_op(op: Union[str, Token]) -> bool: |
| 227 |
"""Returns True if op (string or Token) is an operator that can be used |
| 228 |
as a binary operator in a mathematical operation. |
| 229 |
""" |
| 230 |
ops = ["+", "-", "*", "**", "@", "/", "//", "%"] |
| 231 |
return str(op) in ops |
| 232 |
|
| 233 |
|
| 234 |
def is_operator(op: Union[str, Token]) -> bool: |
| 235 |
"""Returns True if op (string or token) is or could be part of one |
| 236 |
of the following: assigment operator, mathematical operator, |
| 237 |
bitwise operator, comparison operator.""" |
| 238 |
part_ops = ["!", ":"] |
| 239 |
return ( |
| 240 |
is_assignment(op) |
| 241 |
or is_bitwise(op) |
| 242 |
or is_comparison(op) |
| 243 |
or is_math_op(op) |
| 244 |
or str(op) in part_ops |
| 245 |
) |
| 246 |
|
| 247 |
|
| 248 |
def fix_empty_last_line(source: str, tokens: Sequence[Token]) -> None: |
| 249 |
"""Python's tokenizer drops entirely a last line if it consists only of |
| 250 |
space characters and/or tab characters. To ensure that we can always have:: |
| 251 |
|
| 252 |
untokenize(tokenize(source)) == source |
| 253 |
|
| 254 |
we correct the last token content by modifying ``tokens`` in place. |
| 255 |
""" |
| 256 |
if not tokens: |
| 257 |
return |
| 258 |
nb = 0 |
| 259 |
for char in reversed(source): |
| 260 |
if char in (" ", "\t"): |
| 261 |
nb += 1 |
| 262 |
else: |
| 263 |
break |
| 264 |
last_token = tokens.pop() |
| 265 |
|
| 266 |
row = last_token.start_row |
| 267 |
# When dealing with an empty line, Python 3.12 generate an NL token on the last line |
| 268 |
# and adds a ENDMARKER token on the next (non-existent) line. |
| 269 |
# For previous version no NL token was inserted. |
| 270 |
if ( |
| 271 |
sys.version_info >= (3, 12) |
| 272 |
and len(tokens) > 1 |
| 273 |
and tokens[-1].type == py_tokenize.NL |
| 274 |
): |
| 275 |
prev_token = tokens.pop() |
| 276 |
if last_token.start_row != prev_token.start_row: |
| 277 |
row = prev_token.start_row |
| 278 |
|
| 279 |
last_token.string = source[-nb:] |
| 280 |
last_token.start = (row, last_token.start_col) |
| 281 |
last_token.end = (row, last_token.end_col + len(last_token.string)) |
| 282 |
last_token.line = last_token.string |
| 283 |
|
| 284 |
tokens.append(last_token) |
| 285 |
|
| 286 |
|
| 287 |
def tokenize(source: str) -> List[Token]: |
| 288 |
"""Transforms a source (string) into a list of Tokens. |
| 289 |
|
| 290 |
If an exception is raised by Python's tokenize module, the list of tokens |
| 291 |
accumulated up to that point is returned. |
| 292 |
""" |
| 293 |
tokens = [] |
| 294 |
try: |
| 295 |
for tok in py_tokenize.generate_tokens(StringIO(source).readline): |
| 296 |
token = Token(tok) |
| 297 |
tokens.append(token) |
| 298 |
except IndentationError as e: |
| 299 |
try: |
| 300 |
_ignore, linenumber, col, line = e.args[1] |
| 301 |
type_ = py_tokenize.NAME # Not really relevant what we set here |
| 302 |
# except that ERRORTOKEN would cause problems later on. |
| 303 |
start = (linenumber, col) |
| 304 |
end = (linenumber, len(line)) |
| 305 |
string = line[col:].strip() |
| 306 |
token = Token((type_, string, start, end, line)) |
| 307 |
tokens.append(token) |
| 308 |
return tokens |
| 309 |
except Exception as e: # pragma: no cover |
| 310 |
debug_helper.log( |
| 311 |
"after IndentationError, error from token_utils.tokenize()" |
| 312 |
) |
| 313 |
debug_helper.log(repr(e)) |
| 314 |
return tokens |
| 315 |
except (py_tokenize.TokenError, Exception): |
| 316 |
pass |
| 317 |
|
| 318 |
new_source = untokenize(tokens) |
| 319 |
if not source.strip(): # Used to prevent "fix" to be applied to |
| 320 |
return tokens # MEANINGLESS_TOKEN defined elsewhere |
| 321 |
|
| 322 |
if new_source != source: |
| 323 |
length = len(new_source) |
| 324 |
remaining = source[length:] |
| 325 |
if not ( |
| 326 |
remaining.lstrip().startswith(('"""', "'''")) |
| 327 |
or remaining.lstrip().startswith(("'", '"')) |
| 328 |
): |
| 329 |
if sys.version_info >= (3, 12): |
| 330 |
tokens = append_missing_tokens(tokens, remaining) |
| 331 |
return tokens |
| 332 |
elif tokens: |
| 333 |
return add_unclosed_string_content(tokens, remaining, new_source) |
| 334 |
else: |
| 335 |
debug_helper.log("Problem: could not successfully tokenize the source.") |
| 336 |
return [] |
| 337 |
|
| 338 |
if source.endswith((" ", "\t")): |
| 339 |
fix_empty_last_line(source, tokens) |
| 340 |
|
| 341 |
return tokens |
| 342 |
|
| 343 |
|
| 344 |
def add_unclosed_string_content(tokens, remaining, new_source): |
| 345 |
additional_lines = [line + "\n" for line in remaining.split("\n")] |
| 346 |
# removed extra \n added on last line |
| 347 |
additional_lines[-1] = additional_lines[-1][0:-1] |
| 348 |
last_token = tokens[-1] |
| 349 |
string = additional_lines[0] |
| 350 |
if new_source.endswith("\n"): |
| 351 |
start_row = last_token.end_row + 1 |
| 352 |
start_col = 0 |
| 353 |
end_col = len(string) |
| 354 |
line = string |
| 355 |
else: |
| 356 |
spaces_before_quotes = len(string) - len(string.lstrip()) |
| 357 |
start_row = last_token.end_row |
| 358 |
start_col = last_token.end_col + spaces_before_quotes |
| 359 |
string = string.lstrip() |
| 360 |
end_col = start_col + len(string) |
| 361 |
line = last_token.string + string |
| 362 |
end_row = start_row |
| 363 |
tokens.append( |
| 364 |
Token((UNCLOSED, string, (start_row, start_col), (end_row, end_col), line)) |
| 365 |
) |
| 366 |
for line in additional_lines[1:]: |
| 367 |
start_row += 1 |
| 368 |
end_row = start_row |
| 369 |
start_col = 0 |
| 370 |
end_col = len(line) |
| 371 |
tokens.append( |
| 372 |
Token( |
| 373 |
( |
| 374 |
UNCLOSED, |
| 375 |
line, |
| 376 |
(start_row, start_col), |
| 377 |
(end_row, end_col), |
| 378 |
line, |
| 379 |
) |
| 380 |
) |
| 381 |
) |
| 382 |
return tokens |
| 383 |
|
| 384 |
|
| 385 |
def append_missing_tokens(tokens, remaining): |
| 386 |
"""With Python 3.12, the tokenizer changed significantly and can drop content |
| 387 |
when invalid code is encountered. This is an attempt to provide a |
| 388 |
sufficient fix for friendly-traceback. Note that this will not guarantee that |
| 389 |
|
| 390 |
source == untokenize(tokenize(source)) |
| 391 |
|
| 392 |
but should be sufficient for providing the relevant information for |
| 393 |
SyntaxError cases. |
| 394 |
|
| 395 |
See https://github.com/friendly-traceback/friendly-traceback/issues/242. |
| 396 |
""" |
| 397 |
rest_of_line = remaining.split("\n")[0] |
| 398 |
|
| 399 |
if not tokens: |
| 400 |
start_row = 1 |
| 401 |
start_col = 0 |
| 402 |
line = rest_of_line |
| 403 |
else: |
| 404 |
start_row, start_col = tokens[-1].end |
| 405 |
line = tokens[-1].line |
| 406 |
|
| 407 |
stripped_remaining = rest_of_line.lstrip() |
| 408 |
start_col += len(rest_of_line) - len(stripped_remaining) |
| 409 |
|
| 410 |
offset = 0 |
| 411 |
if stripped_remaining.startswith(("0o", "0O")): |
| 412 |
# find first offending digit |
| 413 |
for ch in stripped_remaining: |
| 414 |
if ch in {"8", "9"}: |
| 415 |
break |
| 416 |
offset += 1 |
| 417 |
else: |
| 418 |
debug_helper.log("Did not find disallowed octal digit") |
| 419 |
return tokens |
| 420 |
tok_type = py_tokenize.NUMBER |
| 421 |
tok_string = stripped_remaining[:offset] |
| 422 |
elif is_invisible_control_character(stripped_remaining[0]): |
| 423 |
tok_type = py_tokenize.STRING |
| 424 |
tok_string = stripped_remaining[0] |
| 425 |
else: |
| 426 |
return tokens |
| 427 |
|
| 428 |
tokens.append( |
| 429 |
Token( |
| 430 |
( |
| 431 |
tok_type, |
| 432 |
tok_string, |
| 433 |
(start_row, start_col), |
| 434 |
(start_row, start_col + offset), |
| 435 |
line, |
| 436 |
) |
| 437 |
) |
| 438 |
) |
| 439 |
source_rest = rest_of_line[offset + 1 :] |
| 440 |
|
| 441 |
remaining_tokens = tokenize(source_rest) |
| 442 |
for tok in remaining_tokens: |
| 443 |
if not tok.string: |
| 444 |
tok.line = "" |
| 445 |
else: |
| 446 |
tok.line = line |
| 447 |
if tok.start_col == 0 and tok.string == "": # Endmarker |
| 448 |
tok.start = tok.end = (tok.start_row, tok.start_col) = ( |
| 449 |
tok.end_row, |
| 450 |
tok.end_col, |
| 451 |
) = (start_row + 1, 0) |
| 452 |
else: |
| 453 |
tok.start = (tok.start_row, tok.start_col) = ( |
| 454 |
start_row, |
| 455 |
tok.start_col + start_col + offset, |
| 456 |
) |
| 457 |
tok.end = (tok.end_row, tok.end_col) = ( |
| 458 |
start_row, |
| 459 |
tok.end_col + start_col + offset, |
| 460 |
) |
| 461 |
tokens.append(tok) |
| 462 |
|
| 463 |
return tokens |
| 464 |
|
| 465 |
|
| 466 |
def get_significant_tokens(source: str) -> List[Token]: |
| 467 |
"""Gets a list of tokens from a source (str), ignoring comments |
| 468 |
as well as any token whose string value is either null or |
| 469 |
consists of spaces, newline or tab characters. |
| 470 |
""" |
| 471 |
try: |
| 472 |
tokens = tokenize(source) |
| 473 |
except Exception as e: # pragma: no cover |
| 474 |
debug_helper.log("Exception from token_utils.get_significant_tokens()") |
| 475 |
debug_helper.log_error(e) |
| 476 |
return [] |
| 477 |
return remove_meaningless_tokens(tokens) |
| 478 |
|
| 479 |
|
| 480 |
def remove_meaningless_tokens(tokens: Iterable[Token]) -> List[Token]: |
| 481 |
"""Given a list of tokens, remove all space-like tokens and comments.""" |
| 482 |
new_tokens = [] |
| 483 |
for tok in tokens: |
| 484 |
if not tok.string.strip() or tok.is_comment(): |
| 485 |
continue |
| 486 |
new_tokens.append(tok) |
| 487 |
return new_tokens |
| 488 |
|
| 489 |
|
| 490 |
def get_lines(source: str) -> List[List[Token]]: |
| 491 |
"""Transforms a source (string) into a list of Tokens, with each |
| 492 |
(inner) list containing all the tokens found on a given line of code. |
| 493 |
""" |
| 494 |
lines: List[List[Token]] = [] |
| 495 |
current_row = -1 |
| 496 |
new_line: List[Token] = [] |
| 497 |
tokens = tokenize(source) |
| 498 |
if not tokens: |
| 499 |
return [[]] |
| 500 |
new_line = [tokens[0]] |
| 501 |
|
| 502 |
for token in tokens[1:]: |
| 503 |
if token.start_row != current_row: |
| 504 |
current_row = token.start_row |
| 505 |
if new_line: |
| 506 |
lines.append(new_line) |
| 507 |
new_line = [] |
| 508 |
new_line.append(token) |
| 509 |
lines.append(new_line) |
| 510 |
|
| 511 |
return lines |
| 512 |
|
| 513 |
|
| 514 |
def strip_comment(line: str) -> str: |
| 515 |
"""Removes comments from a line""" |
| 516 |
tokens = [] |
| 517 |
try: |
| 518 |
for tok in py_tokenize.generate_tokens(StringIO(line).readline): |
| 519 |
token = Token(tok) |
| 520 |
if token.is_comment(): |
| 521 |
continue |
| 522 |
if not token.string: |
| 523 |
token.line = "" |
| 524 |
tokens.append(token) |
| 525 |
except py_tokenize.TokenError: |
| 526 |
pass |
| 527 |
return untokenize(tokens) |
| 528 |
|
| 529 |
|
| 530 |
def find_substring_index(main: str, substring: str) -> int: |
| 531 |
"""Somewhat similar to the find() method for strings, |
| 532 |
this function determines if the tokens for substring appear |
| 533 |
as a subsequence of the tokens for main. If so, the index |
| 534 |
of the first token in returned, otherwise -1 is returned. |
| 535 |
""" |
| 536 |
main_tokens = [tok.string for tok in get_significant_tokens(main)] |
| 537 |
sub_tokens = [tok.string for tok in get_significant_tokens(substring)] |
| 538 |
for index, token in enumerate(main_tokens): |
| 539 |
if token == sub_tokens[0]: |
| 540 |
for i, tok in enumerate(main_tokens[index : index + len(sub_tokens)]): |
| 541 |
if tok != sub_tokens[i]: |
| 542 |
break |
| 543 |
else: |
| 544 |
return index |
| 545 |
return -1 |
| 546 |
|
| 547 |
|
| 548 |
def dedent(tokens: Iterable[Union[str, Token]], nb: int) -> List[Token]: |
| 549 |
"""Given a list of tokens, produces an equivalent list corresponding |
| 550 |
to a line of code with the first nb characters removed. |
| 551 |
""" |
| 552 |
line = untokenize(tokens) |
| 553 |
line = line[nb:] |
| 554 |
return tokenize(line) |
| 555 |
|
| 556 |
|
| 557 |
def indent( |
| 558 |
tokens: Iterable[Union[str, Token]], nb: int, tab: bool = False |
| 559 |
) -> List[Token]: |
| 560 |
"""Given a list of tokens, produces an equivalent list corresponding |
| 561 |
to a line of code with nb space characters inserted at the beginning. |
| 562 |
|
| 563 |
If ``tab`` is specified to be ``True``, ``nb`` tab characters are inserted |
| 564 |
instead of spaces. |
| 565 |
""" |
| 566 |
line = untokenize(tokens) |
| 567 |
line = "\t" * nb + line if tab else " " * nb + line |
| 568 |
return tokenize(line) |
| 569 |
|
| 570 |
|
| 571 |
def untokenize(tokens: Iterable[Union[str, Token]]) -> str: |
| 572 |
"""Return source code based on tokens. |
| 573 |
|
| 574 |
This is similar to Python's own tokenize.untokenize(), except that it |
| 575 |
preserves spacing between tokens, by using the line |
| 576 |
information recorded by Python's tokenize.generate_tokens. |
| 577 |
As a result, if the original source code had multiple spaces between |
| 578 |
some tokens or if escaped newlines were used or if tab characters |
| 579 |
were present in the original source, those will also be present |
| 580 |
in the source code produced by untokenize. |
| 581 |
|
| 582 |
Thus ``source == untokenize(tokenize(source))``. |
| 583 |
|
| 584 |
Note: if you you modifying tokens from an original source: |
| 585 |
|
| 586 |
Instead of full token object, ``untokenize`` will accept simple |
| 587 |
strings; however, it will only insert them *as is* without taking them |
| 588 |
into account when it comes with figuring out spacing between tokens. |
| 589 |
""" |
| 590 |
# Adapted from https://github.com/myint/untokenize, |
| 591 |
# Copyright (C) 2013-2018 Steven Myint, MIT License (same as this project). |
| 592 |
|
| 593 |
words = [] |
| 594 |
previous_line = "" |
| 595 |
last_row = 0 |
| 596 |
last_column = -1 |
| 597 |
last_non_whitespace_token_type = None |
| 598 |
|
| 599 |
for token in tokens: |
| 600 |
if isinstance(token, str): # pragma: no cover |
| 601 |
words.append(token) |
| 602 |
continue |
| 603 |
if token.type == py_tokenize.ENCODING: # pragma: no cover |
| 604 |
continue |
| 605 |
|
| 606 |
# Preserve escaped newlines. |
| 607 |
if ( |
| 608 |
last_non_whitespace_token_type != py_tokenize.COMMENT |
| 609 |
and token.start_row > last_row |
| 610 |
and previous_line.endswith(("\\\n", "\\\r\n", "\\\r")) |
| 611 |
): |
| 612 |
words.append(previous_line[len(previous_line.rstrip(" \t\n\r\\")) :]) |
| 613 |
|
| 614 |
# Preserve spacing. |
| 615 |
if token.start_row > last_row: |
| 616 |
last_column = 0 |
| 617 |
if token.start_col > last_column: |
| 618 |
words.append(token.line[last_column : token.start_col]) |
| 619 |
|
| 620 |
words.append(token.string) |
| 621 |
|
| 622 |
previous_line = token.line |
| 623 |
last_row = token.end_row |
| 624 |
last_column = token.end_col |
| 625 |
if not token.is_space(): |
| 626 |
last_non_whitespace_token_type = token.type |
| 627 |
|
| 628 |
return "".join(words) |
| 629 |
|
| 630 |
|
| 631 |
TextOrTokens = Union[str, Sequence[Union[str, Token]]] |
| 632 |
|
| 633 |
|
| 634 |
def print_tokens(source: TextOrTokens) -> None: # pragma: no cover |
| 635 |
"""Prints tokens found in source, excluding spaces and comments. |
| 636 |
|
| 637 |
``source`` is either a string to be tokenized, or a list of Token objects. |
| 638 |
|
| 639 |
This is occasionally useful as a debugging tool. |
| 640 |
""" |
| 641 |
if isinstance(source[0], Token): |
| 642 |
source = untokenize(source) |
| 643 |
|
| 644 |
for lines in get_lines(source): # type: ignore |
| 645 |
for token in lines: |
| 646 |
print(repr(token)) |
| 647 |
print() |
| 648 |
|
| 649 |
|
| 650 |
def is_invisible_control_character(char): |
| 651 |
"""Used to determine if a character would be visible when printed.""" |
| 652 |
if len(char) != 1: # protect against invalid input |
| 653 |
return False |
| 654 |
n = ord(char) |
| 655 |
if 0 <= n <= 0x1F or n == 0x7F or 0x80 <= n <= 0x9F: |
| 656 |
return char |
| 657 |
return False |
| 658 |
|
| 659 |
|
| 660 |
def clone(token): |
| 661 |
return Token( |
| 662 |
[ |
| 663 |
token.type, |
| 664 |
token.string, |
| 665 |
(token.start_row, token.start_col), |
| 666 |
(token.end_row, token.end_col), |
| 667 |
token.line, |
| 668 |
] |
| 669 |
) |