Debian Codegraph @

friendly_traceback/token_utils.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
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 # Python 3.14+ expanded IndentationError.args[1] from 4 to 6 elements.
301 _ignore, linenumber, col, line, *_ = e.args[1]
302 type_ = py_tokenize.NAME # Not really relevant what we set here
303 # except that ERRORTOKEN would cause problems later on.
304 start = (linenumber, col)
305 end = (linenumber, len(line))
306 string = line[col:].strip()
307 token = Token((type_, string, start, end, line))
308 tokens.append(token)
309 return tokens
310 except Exception as e: # pragma: no cover
311 debug_helper.log(
312 "after IndentationError, error from token_utils.tokenize()"
313 )
314 debug_helper.log(repr(e))
315 return tokens
316 except (py_tokenize.TokenError, Exception):
317 pass
318
319 new_source = untokenize(tokens)
320 if not source.strip(): # Used to prevent "fix" to be applied to
321 return tokens # MEANINGLESS_TOKEN defined elsewhere
322
323 if new_source != source:
324 length = len(new_source)
325 remaining = source[length:]
326 if not (
327 remaining.lstrip().startswith(('"""', "'''"))
328 or remaining.lstrip().startswith(("'", '"'))
329 ):
330 if sys.version_info >= (3, 12):
331 tokens = append_missing_tokens(tokens, remaining)
332 return tokens
333 elif tokens:
334 return add_unclosed_string_content(tokens, remaining, new_source)
335 else:
336 debug_helper.log("Problem: could not successfully tokenize the source.")
337 return []
338
339 if source.endswith((" ", "\t")):
340 fix_empty_last_line(source, tokens)
341
342 return tokens
343
344
345 def add_unclosed_string_content(tokens, remaining, new_source):
346 additional_lines = [line + "\n" for line in remaining.split("\n")]
347 # removed extra \n added on last line
348 additional_lines[-1] = additional_lines[-1][0:-1]
349 last_token = tokens[-1]
350 string = additional_lines[0]
351 if new_source.endswith("\n"):
352 start_row = last_token.end_row + 1
353 start_col = 0
354 end_col = len(string)
355 line = string
356 else:
357 spaces_before_quotes = len(string) - len(string.lstrip())
358 start_row = last_token.end_row
359 start_col = last_token.end_col + spaces_before_quotes
360 string = string.lstrip()
361 end_col = start_col + len(string)
362 line = last_token.string + string
363 end_row = start_row
364 tokens.append(
365 Token((UNCLOSED, string, (start_row, start_col), (end_row, end_col), line))
366 )
367 for line in additional_lines[1:]:
368 start_row += 1
369 end_row = start_row
370 start_col = 0
371 end_col = len(line)
372 tokens.append(
373 Token(
374 (
375 UNCLOSED,
376 line,
377 (start_row, start_col),
378 (end_row, end_col),
379 line,
380 )
381 )
382 )
383 return tokens
384
385
386 def append_missing_tokens(tokens, remaining):
387 """With Python 3.12, the tokenizer changed significantly and can drop content
388 when invalid code is encountered. This is an attempt to provide a
389 sufficient fix for friendly-traceback. Note that this will not guarantee that
390
391 source == untokenize(tokenize(source))
392
393 but should be sufficient for providing the relevant information for
394 SyntaxError cases.
395
396 See https://github.com/friendly-traceback/friendly-traceback/issues/242.
397 """
398 rest_of_line = remaining.split("\n")[0]
399
400 if not tokens:
401 start_row = 1
402 start_col = 0
403 line = rest_of_line
404 else:
405 start_row, start_col = tokens[-1].end
406 line = tokens[-1].line
407
408 stripped_remaining = rest_of_line.lstrip()
409 start_col += len(rest_of_line) - len(stripped_remaining)
410
411 offset = 0
412 if stripped_remaining.startswith(("0o", "0O")):
413 # find first offending digit
414 for ch in stripped_remaining:
415 if ch in {"8", "9"}:
416 break
417 offset += 1
418 else:
419 debug_helper.log("Did not find disallowed octal digit")
420 return tokens
421 tok_type = py_tokenize.NUMBER
422 tok_string = stripped_remaining[:offset]
423 elif is_invisible_control_character(stripped_remaining[0]):
424 tok_type = py_tokenize.STRING
425 tok_string = stripped_remaining[0]
426 else:
427 return tokens
428
429 tokens.append(
430 Token(
431 (
432 tok_type,
433 tok_string,
434 (start_row, start_col),
435 (start_row, start_col + offset),
436 line,
437 )
438 )
439 )
440 source_rest = rest_of_line[offset + 1 :]
441
442 remaining_tokens = tokenize(source_rest)
443 for tok in remaining_tokens:
444 if not tok.string:
445 tok.line = ""
446 else:
447 tok.line = line
448 if tok.start_col == 0 and tok.string == "": # Endmarker
449 tok.start = tok.end = (tok.start_row, tok.start_col) = (
450 tok.end_row,
451 tok.end_col,
452 ) = (start_row + 1, 0)
453 else:
454 tok.start = (tok.start_row, tok.start_col) = (
455 start_row,
456 tok.start_col + start_col + offset,
457 )
458 tok.end = (tok.end_row, tok.end_col) = (
459 start_row,
460 tok.end_col + start_col + offset,
461 )
462 tokens.append(tok)
463
464 return tokens
465
466
467 def get_significant_tokens(source: str) -> List[Token]:
468 """Gets a list of tokens from a source (str), ignoring comments
469 as well as any token whose string value is either null or
470 consists of spaces, newline or tab characters.
471 """
472 try:
473 tokens = tokenize(source)
474 except Exception as e: # pragma: no cover
475 debug_helper.log("Exception from token_utils.get_significant_tokens()")
476 debug_helper.log_error(e)
477 return []
478 return remove_meaningless_tokens(tokens)
479
480
481 def remove_meaningless_tokens(tokens: Iterable[Token]) -> List[Token]:
482 """Given a list of tokens, remove all space-like tokens and comments."""
483 new_tokens = []
484 for tok in tokens:
485 if not tok.string.strip() or tok.is_comment():
486 continue
487 new_tokens.append(tok)
488 return new_tokens
489
490
491 def get_lines(source: str) -> List[List[Token]]:
492 """Transforms a source (string) into a list of Tokens, with each
493 (inner) list containing all the tokens found on a given line of code.
494 """
495 lines: List[List[Token]] = []
496 current_row = -1
497 new_line: List[Token] = []
498 tokens = tokenize(source)
499 if not tokens:
500 return [[]]
501 new_line = [tokens[0]]
502
503 for token in tokens[1:]:
504 if token.start_row != current_row:
505 current_row = token.start_row
506 if new_line:
507 lines.append(new_line)
508 new_line = []
509 new_line.append(token)
510 lines.append(new_line)
511
512 return lines
513
514
515 def strip_comment(line: str) -> str:
516 """Removes comments from a line"""
517 tokens = []
518 try:
519 for tok in py_tokenize.generate_tokens(StringIO(line).readline):
520 token = Token(tok)
521 if token.is_comment():
522 continue
523 if not token.string:
524 token.line = ""
525 tokens.append(token)
526 except py_tokenize.TokenError:
527 pass
528 return untokenize(tokens)
529
530
531 def find_substring_index(main: str, substring: str) -> int:
532 """Somewhat similar to the find() method for strings,
533 this function determines if the tokens for substring appear
534 as a subsequence of the tokens for main. If so, the index
535 of the first token in returned, otherwise -1 is returned.
536 """
537 main_tokens = [tok.string for tok in get_significant_tokens(main)]
538 sub_tokens = [tok.string for tok in get_significant_tokens(substring)]
539 for index, token in enumerate(main_tokens):
540 if token == sub_tokens[0]:
541 for i, tok in enumerate(main_tokens[index : index + len(sub_tokens)]):
542 if tok != sub_tokens[i]:
543 break
544 else:
545 return index
546 return -1
547
548
549 def dedent(tokens: Iterable[Union[str, Token]], nb: int) -> List[Token]:
550 """Given a list of tokens, produces an equivalent list corresponding
551 to a line of code with the first nb characters removed.
552 """
553 line = untokenize(tokens)
554 line = line[nb:]
555 return tokenize(line)
556
557
558 def indent(
559 tokens: Iterable[Union[str, Token]], nb: int, tab: bool = False
560 ) -> List[Token]:
561 """Given a list of tokens, produces an equivalent list corresponding
562 to a line of code with nb space characters inserted at the beginning.
563
564 If ``tab`` is specified to be ``True``, ``nb`` tab characters are inserted
565 instead of spaces.
566 """
567 line = untokenize(tokens)
568 line = "\t" * nb + line if tab else " " * nb + line
569 return tokenize(line)
570
571
572 def untokenize(tokens: Iterable[Union[str, Token]]) -> str:
573 """Return source code based on tokens.
574
575 This is similar to Python's own tokenize.untokenize(), except that it
576 preserves spacing between tokens, by using the line
577 information recorded by Python's tokenize.generate_tokens.
578 As a result, if the original source code had multiple spaces between
579 some tokens or if escaped newlines were used or if tab characters
580 were present in the original source, those will also be present
581 in the source code produced by untokenize.
582
583 Thus ``source == untokenize(tokenize(source))``.
584
585 Note: if you you modifying tokens from an original source:
586
587 Instead of full token object, ``untokenize`` will accept simple
588 strings; however, it will only insert them *as is* without taking them
589 into account when it comes with figuring out spacing between tokens.
590 """
591 # Adapted from https://github.com/myint/untokenize,
592 # Copyright (C) 2013-2018 Steven Myint, MIT License (same as this project).
593
594 words = []
595 previous_line = ""
596 last_row = 0
597 last_column = -1
598 last_non_whitespace_token_type = None
599
600 for token in tokens:
601 if isinstance(token, str): # pragma: no cover
602 words.append(token)
603 continue
604 if token.type == py_tokenize.ENCODING: # pragma: no cover
605 continue
606
607 # Preserve escaped newlines.
608 if (
609 last_non_whitespace_token_type != py_tokenize.COMMENT
610 and token.start_row > last_row
611 and previous_line.endswith(("\\\n", "\\\r\n", "\\\r"))
612 ):
613 words.append(previous_line[len(previous_line.rstrip(" \t\n\r\\")) :])
614
615 # Preserve spacing.
616 if token.start_row > last_row:
617 last_column = 0
618 if token.start_col > last_column:
619 words.append(token.line[last_column : token.start_col])
620
621 words.append(token.string)
622
623 previous_line = token.line
624 last_row = token.end_row
625 last_column = token.end_col
626 if not token.is_space():
627 last_non_whitespace_token_type = token.type
628
629 return "".join(words)
630
631
632 TextOrTokens = Union[str, Sequence[Union[str, Token]]]
633
634
635 def print_tokens(source: TextOrTokens) -> None: # pragma: no cover
636 """Prints tokens found in source, excluding spaces and comments.
637
638 ``source`` is either a string to be tokenized, or a list of Token objects.
639
640 This is occasionally useful as a debugging tool.
641 """
642 if isinstance(source[0], Token):
643 source = untokenize(source)
644
645 for lines in get_lines(source): # type: ignore
646 for token in lines:
647 print(repr(token))
648 print()
649
650
651 def is_invisible_control_character(char):
652 """Used to determine if a character would be visible when printed."""
653 if len(char) != 1: # protect against invalid input
654 return False
655 n = ord(char)
656 if 0 <= n <= 0x1F or n == 0x7F or 0x80 <= n <= 0x9F:
657 return char
658 return False
659
660
661 def clone(token):
662 return Token(
663 [
664 token.type,
665 token.string,
666 (token.start_row, token.start_col),
667 (token.end_row, token.end_col),
668 token.line,
669 ]
670 )