| 1 |
import os |
| 2 |
from typing import Iterable |
| 3 |
|
| 4 |
import stack_data |
| 5 |
from executing import only |
| 6 |
from stack_data import LINE_GAP, BlankLineRange, BlankLines, Formatter, Line, Options |
| 7 |
from stack_data.utils import cached_property |
| 8 |
|
| 9 |
from friendly_traceback import token_utils |
| 10 |
|
| 11 |
from . import debug_helper |
| 12 |
from .ft_gettext import current_lang |
| 13 |
from .source_cache import cache |
| 14 |
|
| 15 |
_ = current_lang.translate |
| 16 |
|
| 17 |
|
| 18 |
class FriendlyFormatter(Formatter): |
| 19 |
def __init__( |
| 20 |
self, |
| 21 |
**kwargs, |
| 22 |
): |
| 23 |
self.indent = " " |
| 24 |
super().__init__(**kwargs) |
| 25 |
|
| 26 |
def format_frame_source(self, frame: stack_data.FrameInfo) -> Iterable[str]: |
| 27 |
for line in frame.lines: |
| 28 |
if isinstance(line, Line): |
| 29 |
yield self.format_line(line) |
| 30 |
elif isinstance(line, BlankLineRange): |
| 31 |
yield self.format_blank_lines_linenumbers(line) |
| 32 |
else: |
| 33 |
assert line is LINE_GAP |
| 34 |
yield self.indent + self.line_gap_string + "\n" |
| 35 |
|
| 36 |
def format_line(self, line: Line) -> str: |
| 37 |
result = self.indent |
| 38 |
if line.is_current: |
| 39 |
result += self.current_line_indicator |
| 40 |
else: |
| 41 |
result += " " * len(self.current_line_indicator) |
| 42 |
result += self.line_number_format_string.format(line.lineno) |
| 43 |
prefix = result |
| 44 |
result += line.render() + "\n" |
| 45 |
|
| 46 |
for line_range in line.executing_node_ranges: |
| 47 |
start = line_range.start - line.leading_indent |
| 48 |
end = line_range.end - line.leading_indent |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
if end > start: |
| 53 |
result += ( |
| 54 |
" " * (start + len(prefix)) |
| 55 |
+ self.executing_node_underline * (end - start) |
| 56 |
+ "\n" |
| 57 |
) |
| 58 |
return result |
| 59 |
|
| 60 |
def format_blank_lines_linenumbers(self, blank_line): |
| 61 |
result = self.indent + " " * len(self.current_line_indicator) |
| 62 |
if blank_line.begin_lineno == blank_line.end_lineno: |
| 63 |
return ( |
| 64 |
result |
| 65 |
+ self.line_number_format_string.format(blank_line.begin_lineno) |
| 66 |
+ "\n" |
| 67 |
) |
| 68 |
return result + "{}\n".format(self.line_number_gap_string) |
| 69 |
|
| 70 |
|
| 71 |
class FrameInfo(stack_data.FrameInfo): |
| 72 |
@cached_property |
| 73 |
def partial_source(self) -> str: |
| 74 |
return self._partial_source(with_node_range=False) |
| 75 |
|
| 76 |
@cached_property |
| 77 |
def partial_source_with_node_range(self) -> str: |
| 78 |
return self._partial_source(with_node_range=True) |
| 79 |
|
| 80 |
def _partial_source(self, with_node_range: bool) -> str: |
| 81 |
"""Gets the part of the source where an exception occurred, |
| 82 |
formatted in a pre-determined way, as well as the content |
| 83 |
of the specific line where the exception occurred. |
| 84 |
""" |
| 85 |
file_not_found = _("Problem: source of `{filename}` is not available\n").format( |
| 86 |
filename=self.filename |
| 87 |
) |
| 88 |
source = "" |
| 89 |
|
| 90 |
if not self.lines and self.filename: |
| 91 |
|
| 92 |
try: |
| 93 |
lineno = self.lineno |
| 94 |
s_lines = cache.get_source_lines(self.filename) |
| 95 |
self.lines = [] |
| 96 |
with_node_range = False |
| 97 |
linenumber = max(lineno - 2, 0) |
| 98 |
for line in s_lines[linenumber : lineno + 1]: |
| 99 |
self.lines.append(FakeLineObject(line, linenumber, lineno)) |
| 100 |
linenumber += 1 |
| 101 |
except Exception as e: |
| 102 |
debug_helper.log_error(e) |
| 103 |
|
| 104 |
if self.lines: |
| 105 |
source = self._highlighted_source(with_node_range) |
| 106 |
elif self.filename and os.path.abspath(self.filename): |
| 107 |
if self.filename not in ["<stdin>", "<string>"]: |
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
source = file_not_found |
| 113 |
debug_helper.log("Problem in get_partial_source().") |
| 114 |
debug_helper.log(file_not_found) |
| 115 |
elif not self.filename: |
| 116 |
source = file_not_found |
| 117 |
debug_helper.log("Problem in get_partial_source().") |
| 118 |
debug_helper.log(file_not_found) |
| 119 |
else: |
| 120 |
debug_helper.log("Problem in get_partial_source().") |
| 121 |
debug_helper.log("Should not have reached this option") |
| 122 |
debug_helper.log_error() |
| 123 |
|
| 124 |
if not source.endswith("\n"): |
| 125 |
source += "\n" |
| 126 |
|
| 127 |
return source |
| 128 |
|
| 129 |
@cached_property |
| 130 |
def highlighted_source(self) -> str: |
| 131 |
return self._highlighted_source(with_node_range=False) |
| 132 |
|
| 133 |
def problem_line(self) -> str: |
| 134 |
if not self.lines: |
| 135 |
return "" |
| 136 |
for line_obj in self.lines: |
| 137 |
if line_obj is stack_data.LINE_GAP: |
| 138 |
continue |
| 139 |
elif isinstance(line_obj, stack_data.BlankLineRange): |
| 140 |
continue |
| 141 |
elif line_obj.is_current: |
| 142 |
return str(line_obj.text) |
| 143 |
return "" |
| 144 |
|
| 145 |
def _highlighted_source(self, with_node_range: bool) -> str: |
| 146 |
"""Extracts a few relevant lines from a file content given as a list |
| 147 |
of lines, adding line number information and identifying |
| 148 |
a particular line. |
| 149 |
|
| 150 |
When dealing with a ``SyntaxError`` or its subclasses, offset is an |
| 151 |
integer normally used by Python to indicate the position of |
| 152 |
the error with a ``^``, like:: |
| 153 |
|
| 154 |
if True |
| 155 |
^ |
| 156 |
|
| 157 |
which, in this case, points to a missing colon. We use the same |
| 158 |
representation in this case. |
| 159 |
""" |
| 160 |
lines = self.lines |
| 161 |
|
| 162 |
if not lines: |
| 163 |
return "", "" |
| 164 |
|
| 165 |
nb_digits = len(str(lines[-1].lineno)) |
| 166 |
lineno_fmt_string = "{:%d}| " % nb_digits |
| 167 |
line_gap_string = " " * nb_digits + "(...)" |
| 168 |
line_number_gap_string = " " * (nb_digits - 1) + ":" |
| 169 |
|
| 170 |
try: |
| 171 |
new_lines = [ |
| 172 |
line |
| 173 |
for line in FriendlyFormatter( |
| 174 |
options=Options(blank_lines=BlankLines.SINGLE), |
| 175 |
line_number_format_string=lineno_fmt_string, |
| 176 |
line_gap_string=line_gap_string, |
| 177 |
line_number_gap_string=line_number_gap_string, |
| 178 |
).format_frame_source(self) |
| 179 |
] |
| 180 |
|
| 181 |
return "".join(new_lines) |
| 182 |
except Exception: |
| 183 |
return "<NO SOURCE>" |
| 184 |
|
| 185 |
@cached_property |
| 186 |
def node_info(self): |
| 187 |
"""Finds the 'node', that is the exact part of a line of code |
| 188 |
that is related to the cause of the problem. |
| 189 |
""" |
| 190 |
try: |
| 191 |
ex = self.executing |
| 192 |
node = ex.node |
| 193 |
node_text = ex.text() |
| 194 |
except Exception as e: |
| 195 |
debug_helper.log("Exception raised in TracebackData.use_executing.") |
| 196 |
debug_helper.log(str(e)) |
| 197 |
return |
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
special_case = False |
| 216 |
if not node_text: |
| 217 |
node_text = self.handle_special_cases() |
| 218 |
special_case = True |
| 219 |
if not node_text: |
| 220 |
|
| 221 |
try: |
| 222 |
tokens = token_utils.tokenize(self.current_line.text) |
| 223 |
tokens = token_utils.remove_meaningless_tokens(tokens) |
| 224 |
return ( |
| 225 |
None, |
| 226 |
(tokens[0].start_col, tokens[-1].end_col), |
| 227 |
self.current_line.text, |
| 228 |
) |
| 229 |
except Exception: |
| 230 |
return None |
| 231 |
|
| 232 |
node_range = None |
| 233 |
bad_line = self.current_line.text |
| 234 |
if node_text and node_text in bad_line: |
| 235 |
begin = bad_line.find(node_text) |
| 236 |
end = begin + len(node_text) |
| 237 |
node_range = begin, end |
| 238 |
if special_case: |
| 239 |
|
| 240 |
return node, node_range, bad_line |
| 241 |
return node, node_range, node_text |
| 242 |
|
| 243 |
@cached_property |
| 244 |
def current_line(self): |
| 245 |
return only( |
| 246 |
line for line in self.lines if isinstance(line, Line) and line.is_current |
| 247 |
) |
| 248 |
|
| 249 |
def handle_special_cases(self) -> str: |
| 250 |
"""Hack to try to identify a problematic text when node_text is None. |
| 251 |
|
| 252 |
We just use the information to highlight where in a statement |
| 253 |
the error is located. |
| 254 |
""" |
| 255 |
try: |
| 256 |
exec(self.current_line.text) |
| 257 |
except Exception as exc: |
| 258 |
saved_exc = exc |
| 259 |
else: |
| 260 |
return "" |
| 261 |
|
| 262 |
if not hasattr(saved_exc, "msg"): |
| 263 |
return "" |
| 264 |
message = saved_exc.msg |
| 265 |
if message.startswith("cannot import name '"): |
| 266 |
return message.split("'")[1] |
| 267 |
elif message.startswith("No module named '"): |
| 268 |
return message.split("'")[1] |
| 269 |
|
| 270 |
return "" |
| 271 |
|
| 272 |
|
| 273 |
class FakeLineObject: |
| 274 |
"""Class reproducing the minimum attributes for formatting lines""" |
| 275 |
|
| 276 |
def __init__(self, line, linenumber, lineno): |
| 277 |
self.text = line |
| 278 |
self.lineno = linenumber + 1 |
| 279 |
self.is_current = linenumber == lineno - 1 |
| 280 |
|
| 281 |
def __repr__(self): |
| 282 |
return f"lineno: {self.lineno}; current: {self.is_current}; {self.text}" |