| 66 | |
| 67 | |
| 68 | class Interp(ReplInterpreter): |
| 69 | def __init__( |
| 70 | self, |
| 71 | locals: dict[str, Any] | None = None, |
| 72 | ) -> None: |
| 73 | """Constructor. |
| 74 | |
| 75 | We include an argument for the outfile to pass to the formatter for it |
| 76 | to write to. |
| 77 | """ |
| 78 | super().__init__(locals) |
| 79 | |
| 80 | # typically changed after being instantiated |
| 81 | # but used when interpreter used corresponding REPL |
| 82 | def write(err_line: str | FmtStr) -> None: |
| 83 | """Default stderr handler for tracebacks |
| 84 | |
| 85 | Accepts FmtStrs so interpreters can output them""" |
| 86 | sys.stderr.write(str(err_line)) |
| 87 | |
| 88 | self.write = write # type: ignore |
| 89 | self.outfile = self |
| 90 | |
| 91 | def writetb(self, lines: Iterable[str]) -> None: |
| 92 | tbtext = "".join(lines) |
| 93 | lexer = get_lexer_by_name("pytb") |
| 94 | self.format(tbtext, lexer) |
| 95 | # TODO for tracebacks get_lexer_by_name("pytb", stripall=True) |
| 96 | |
| 97 | def format(self, tbtext: str, lexer: Any) -> None: |
| 98 | # FIXME: lexer should be "Lexer" |
| 99 | traceback_informative_formatter = BPythonFormatter(default_colors) |
| 100 | traceback_code_formatter = BPythonFormatter({Token: "d"}) |
| 101 | |
| 102 | no_format_mode = False |
| 103 | cur_line = [] |
| 104 | for token, text in lexer.get_tokens(tbtext): |
| 105 | if text.endswith("\n"): |
| 106 | cur_line.append((token, text)) |
| 107 | if no_format_mode: |
| 108 | traceback_code_formatter.format(cur_line, self.outfile) |
| 109 | no_format_mode = False |
| 110 | else: |
| 111 | traceback_informative_formatter.format( |
| 112 | cur_line, self.outfile |
| 113 | ) |
| 114 | cur_line = [] |
| 115 | elif text == " " and len(cur_line) == 0: |
| 116 | no_format_mode = True |
| 117 | cur_line.append((token, text)) |
| 118 | else: |
| 119 | cur_line.append((token, text)) |
| 120 | assert cur_line == [], cur_line |
| 121 | |
| 122 | |
| 123 | def code_finished_will_parse( |