|
76 | 76 | import dis
|
77 | 77 | import code
|
78 | 78 | import glob
|
| 79 | +import token |
79 | 80 | import codeop
|
80 | 81 | import pprint
|
81 | 82 | import signal
|
@@ -601,6 +602,39 @@ def default(self, line):
|
601 | 602 | except:
|
602 | 603 | self._error_exc()
|
603 | 604 |
|
| 605 | + def _replace_convenience_variables(self, line): |
| 606 | + """Replace the convenience variables in 'line' with their values. |
| 607 | + e.g. $foo is replaced by __pdb_convenience_variables["foo"]. |
| 608 | + Note: such pattern in string literals will be skipped""" |
| 609 | + |
| 610 | + if "$" not in line: |
| 611 | + return line |
| 612 | + |
| 613 | + dollar_start = dollar_end = -1 |
| 614 | + replace_variables = [] |
| 615 | + try: |
| 616 | + for t in tokenize.generate_tokens(io.StringIO(line).readline): |
| 617 | + token_type, token_string, start, end, _ = t |
| 618 | + if token_type == token.OP and token_string == '$': |
| 619 | + dollar_start, dollar_end = start, end |
| 620 | + elif start == dollar_end and token_type == token.NAME: |
| 621 | + # line is a one-line command so we only care about column |
| 622 | + replace_variables.append((dollar_start[1], end[1], token_string)) |
| 623 | + except tokenize.TokenError: |
| 624 | + return line |
| 625 | + |
| 626 | + if not replace_variables: |
| 627 | + return line |
| 628 | + |
| 629 | + last_end = 0 |
| 630 | + line_pieces = [] |
| 631 | + for start, end, name in replace_variables: |
| 632 | + line_pieces.append(line[last_end:start] + f'__pdb_convenience_variables["{name}"]') |
| 633 | + last_end = end |
| 634 | + line_pieces.append(line[last_end:]) |
| 635 | + |
| 636 | + return ''.join(line_pieces) |
| 637 | + |
604 | 638 | def precmd(self, line):
|
605 | 639 | """Handle alias expansion and ';;' separator."""
|
606 | 640 | if not line.strip():
|
@@ -635,7 +669,7 @@ def precmd(self, line):
|
635 | 669 | line = line[:marker].rstrip()
|
636 | 670 |
|
637 | 671 | # Replace all the convenience variables
|
638 |
| - line = re.sub(r'\$([a-zA-Z_][a-zA-Z0-9_]*)', r'__pdb_convenience_variables["\1"]', line) |
| 672 | + line = self._replace_convenience_variables(line) |
639 | 673 |
|
640 | 674 | return line
|
641 | 675 |
|
|
0 commit comments