Debian Codegraph @

friendly_traceback/syntax_errors/source_info.py

raw symbols SCIP
1 # type: ignore
2 """Contains a class that compiles and stores all the information that
3 is relevant to the analysis of SyntaxErrors.
4 """
5
6 from .. import debug_helper, token_utils
7 from ..source_cache import cache
8 from .syntax_utils import matching_brackets
9
10 # During the analysis for finding the cause of the error, we typically examine
11 # a "bad token" identified by Python as the cause of the error and often
12 # look at its two neighbours. If the bad token is the first one in a statement
13 # it does not have a token preceding it; if it is the last one, it does not
14 # have a token following it. By assigning a meaningless token value to these
15 # neighbours, the code for the analysis can be greatly simplified as we do
16 # not have to verify the existence of these neighbours.
17 MEANINGLESS_TOKEN = token_utils.tokenize(" ")[0]
18 # fmt: off
19 LINE_NUMBER = " {:%d}| " # noqa
20 MARKED_LINE_NUMBER = " -->{:%d}| " # noqa
21 LINE_GAP = " (...)" # noqa
22 # fmt: on
23
24
25 class Statement:
26 """Instances of this class contain all relevant information required
27 for the various functions that attempt to determine the cause of
28 SyntaxError.
29
30 One main idea is to retrieve a "complete statement" where the
31 exception is raised. By "complete statement", we mean the smallest
32 number of consecutive lines of code that contains the line where
33 the exception was raised and includes matching pairs of brackets,
34 (), [], {}. If a problem arises due to non-matching pairs of brackets,
35 this information is available (variables begin_brackets or end_bracket).
36
37 A complete statement is saved as a list of tokens (self.statement_tokens)
38 from which it could be reconstructed using an untokenize function.
39
40 From this list of tokens, a secondary list is obtained (self.tokens) by
41 removing all space-like and comment tokens; this secondary list
42 thus includes the only meaningful tokens needed to do the analysis.
43
44 To simplify the code doing the error analysis itself, we precompute various
45 parameters (e.g. does the statement fits on a single line, how many
46 meaningful tokens are included, what are the first and last tokens
47 on that statement, etc.) which are needed for some functions.
48 """
49
50 def __init__(self, value, bad_line, original_bad_line):
51 # The basic information given by a SyntaxError
52 self.filename = value.filename
53 self.linenumber = value.lineno
54 self.message = value.msg
55 self.offset = value.offset
56 self.value = value # can be useful when debugging with the repl
57
58 # Python 3.10 introduced new attributes for 'value'.
59 # We already have taken care of assigning some default values
60 # to these in core.py.
61 self.end_offset = value.end_offset
62 self.end_linenumber = value.end_lineno
63
64 if self.end_offset is None or self.offset is None:
65 self.highlighted_tokens = None
66 elif self.end_offset - self.offset == 1:
67 self.highlighted_tokens = None
68 else:
69 self.highlighted_tokens = []
70
71 # From the traceback, we were previously able ot obtain the line
72 # of code identified by Python as being problematic.
73 self.bad_line = bad_line # previously obtained from the traceback
74 self.original_bad_line = original_bad_line
75 # skipcq: PTC-W0052
76 self.entire_statement = original_bad_line # temporary assignment
77
78 # The following will be obtained using offset and bad_line
79 self.bad_token = None
80 self.bad_token_index = 0
81 self.prev_token = None # meaningful token preceding bad token
82 self.next_token = None # meaningful token following bad token
83 self.bad_token_comment = None
84
85 # SyntaxError produced inside f-strings occasionally require a special treatment
86 self.fstring_error = self.filename == "<fstring>" or "f-string" in self.message
87
88 self.all_statements = [] # useful to determine what lines to include in
89 # the contextual display
90
91 # statement_tokens includes all tokens, including newlines, etc., needed
92 self.statement_tokens = [] # for proper reconstruction of multiline statements
93 self.tokens = [] # meaningful tokens, used for error analysis; see docstring
94 self.nb_tokens = 0 # number of meaningful tokens
95 self.formatted_partial_source = ""
96 self.source_lines = [] # lines of code for the source
97
98 self.statement_brackets = [] # keep track of ([{ anywhere in a statement
99 self.begin_brackets = [] # unclosed ([{ before bad token
100 self.end_bracket = None # single unmatched )]}
101
102 self.first_token = None # meaningful token
103 self.last_token = None # meaningful token
104
105 # The following is used to indicate the position of ^ and other
106 # symbols when using where()
107 self.location_markers = {}
108
109 # When using the friendly console (repl), SyntaxError might prevent
110 # closing all brackets to complete a statement. Knowing this can be
111 # useful during the error analysis.
112 self.using_friendly_console = False
113 if self.filename is not None:
114 self.using_friendly_console = self.filename.startswith("<friendly")
115 elif not self.exceptional_case(): # pragma: no cover
116 debug_helper.log("filename is None in source_info.Statement")
117 debug_helper.log("Add this as a new test.")
118
119 self.get_token_info()
120
121 def exceptional_case(self):
122 """Returns True if a case that is known to not have all the required information
123 available, such as filename or linenumber."""
124 return (
125 "too many statically nested blocks" in self.message
126 or "encoding problem" in self.message
127 )
128
129 def get_token_info(self):
130 """Obtain all the relevant information about the tokens in
131 the file, with particular emphasis on the tokens belonging
132 to the statement where the error is located.
133 """
134 if self.linenumber is not None:
135 source_tokens = self.get_source_tokens()
136 # self.all_statements and self.statement_tokens are set in the following
137 self.obtain_statement(source_tokens)
138 self.tokens = self.remove_meaningless_tokens()
139 current_statement_index = len(self.all_statements) - 1
140 if not self.tokens:
141 while current_statement_index > 0:
142 self.statement_tokens = self.all_statements[current_statement_index]
143 current_statement_index -= 1
144 self.tokens = self.remove_meaningless_tokens()
145 if self.tokens:
146 break
147 else:
148 self.tokens = [token_utils.tokenize("Internal_error")[0]]
149
150 self.entire_statement = token_utils.untokenize(self.statement_tokens)
151 if (
152 self.filename.startswith("<friendly-console")
153 and self.statement_brackets
154 and not self.end_bracket
155 ): # pragma: no cover
156 # We got an error flagged before we had the chance to close
157 # brackets. Unclosed brackets should not be a problem on their
158 # own in a console session - so, we make sure to close
159 # the brackets in order to be able to find the true cause
160 # of the error
161 add_token = ""
162 brackets = self.statement_brackets.copy()
163 while brackets:
164 bracket = brackets.pop()
165 if bracket == "(":
166 add_token += ")"
167 elif bracket == "[":
168 add_token += "]"
169 else:
170 add_token += "}"
171
172 if self.tokens[0].string in [
173 "class",
174 "def",
175 "if",
176 "elif",
177 "while",
178 "for",
179 "except",
180 "with",
181 ]:
182 add_token += ":"
183
184 last_token = self.tokens[-1]
185 last_token = last_token.copy()
186 last_token.start_row += 1
187 last_token.string = last_token.line = add_token
188 self.tokens.append(last_token)
189
190 elif not self.exceptional_case(): # pragma: no cover
191 debug_helper.log("linenumber is None in source_info.Statement")
192 debug_helper.log("Add this as new test case")
193
194 if self.tokens:
195 self.assign_individual_token_values()
196 if self.tokens[-1].is_unclosed_string():
197 self.bad_line = self.entire_statement
198 elif not self.exceptional_case(): # pragma: no cover
199 debug_helper.log("No meaningful tokens in source_info.Statement")
200
201 def get_source_tokens(self):
202 """Returns a list containing all the tokens from the source."""
203 source = ""
204 if "f-string: invalid syntax" in self.message:
205 source = self.bad_line
206 try:
207 exec(self.bad_line)
208 except SyntaxError as e:
209 self.offset = e.offset
210 self.linenumber = 1
211 if not source.strip():
212 self.source_lines = cache.get_source_lines(self.filename)
213 if self.source_lines == ["\n"]:
214 self.source_lines = ["...\n"] * (self.linenumber - 1)
215 self.source_lines.append(self.bad_line)
216 source = "".join(self.source_lines)
217 if not source.strip():
218 source = self.bad_line or "\n"
219 return token_utils.tokenize(source)
220
221 def assign_individual_token_values(self):
222 """Assign values of previous and next to bad token and other
223 related values.
224 """
225 self.nb_tokens = len(self.tokens)
226 if self.nb_tokens >= 1:
227 self.first_token = self.tokens[0]
228 self.last_token = self.tokens[-1]
229
230 if self.bad_token is None:
231 self.bad_token = self.last_token
232 self.bad_token_index = self.nb_tokens - 1
233 if self.bad_token_index == 0:
234 self.prev_token = MEANINGLESS_TOKEN
235 else:
236 self.prev_token = self.tokens[self.bad_token_index - 1]
237
238 if self.bad_token_index == 0:
239 self.prev_token = MEANINGLESS_TOKEN
240 elif self.prev_token is None: # pragma: no cover
241 debug_helper.log("This case should be added as new test.")
242 self.prev_token = self.tokens[self.bad_token_index - 1]
243
244 if self.last_token != self.bad_token:
245 self.next_token = self.tokens[self.bad_token_index + 1]
246 else:
247 self.next_token = MEANINGLESS_TOKEN
248
249 def format_statement(self):
250 """Format the statement identified as causing the problem and possibly
251 a couple of preceding statements, showing the line number and token identified.
252 """
253 # Some errors, like "Too many statistically nested blocs" prevent
254 # Python from making a source available.
255 if not (self.statement_tokens or self.original_bad_line.strip("\n")):
256 self.formatted_partial_source = ""
257 return
258
259 # In some IndentationError cases, and possibly others,
260 # Python shows the ^ just before the first token
261 # Note that start_row from tokenize and self.offset differ in their origins.
262 offset_col = self.tokens[-1].start_col
263 if self.offset == offset_col:
264 self.offset += 1
265 self.end_offset += 1
266
267 if self.statement_tokens:
268 lines = self.get_lines_to_show()
269 else:
270 lines = [(self.linenumber, self.original_bad_line.strip("\n"))]
271 self.annotate_lines(lines)
272
273 def get_lines_to_show(self):
274 """Restricts the lines of code to be included when showing the location
275 of the error.
276 """
277 self.create_location_markers()
278 first_token = self.all_statements[0][0]
279 lines = get_lines_from_statement(
280 self.statement_tokens, self.linenumber, first_token
281 )
282 if lines:
283 last_linenumber_included, _ = lines[-1]
284 if self.linenumber > last_linenumber_included:
285 # The problem line was an empty line
286 lines.append((last_linenumber_included + 1, ""))
287 return lines
288
289 def annotate_lines(self, lines):
290 """Adds the caret marks used to show the location of the error"""
291 # Lines is a list of tuples, each tuple has the line number
292 # as a first item, and the text of the line as the second.
293
294 if lines:
295 # Ensures that we align all the lines vertically on a colon
296 # following the line number, even if the number of digits
297 # changes, i.e. we include lines 8, 9, 10, 11.
298 nb_digits = len(str(lines[-1][0]))
299 else:
300 debug_helper.log("No line to annotate in annotate_lines")
301 self.formatted_partial_source = "\n"
302 return
303 no_mark = LINE_NUMBER % nb_digits
304 with_mark = MARKED_LINE_NUMBER % nb_digits if len(lines) > 1 else no_mark
305 leading_spaces = " " * (len(LINE_NUMBER % lines[-1][0]) - 3)
306
307 new_lines = []
308 for i, line in lines:
309 if i in self.location_markers:
310 num = with_mark.format(i)
311 new_lines.append(num + line)
312 new_lines.append(leading_spaces + self.location_markers[i])
313 else:
314 num = no_mark.format(i)
315 new_lines.append(num + line)
316
317 self.formatted_partial_source = "\n".join(new_lines)
318
319 def create_location_markers(self):
320 # In some cases, the location markers are determined while analysing
321 # the statement to find the cause.
322 if self.location_markers:
323 return
324 # We generally go with the information obtained by Python.
325 # although, sometimes it might be off by 1.
326 nb_carets = 1 # Python default
327 diff = self.bad_token.start_col - self.offset
328 self.offset += diff
329 nb_carets = 0
330 if self.highlighted_tokens:
331 last_token = self.highlighted_tokens[-1]
332 if last_token.is_comment() and not (last_token is self.bad_token):
333 last_token = self.highlighted_tokens[-2]
334 if self.end_offset is not None:
335 if self.end_offset < last_token.end_col:
336 nb_carets = self.end_offset - self.bad_token.start_col
337 else:
338 nb_carets = last_token.end_col - self.bad_token.start_col
339 # Highlight at least the entire bad token for friendly
340 nb_carets = max(len(self.bad_token.string), nb_carets)
341 offset_mark = " " * self.offset + "^" * nb_carets
342 self.location_markers = {self.linenumber: offset_mark}
343
344 def obtain_statement(self, source_tokens):
345 """This method scans the source searching for the statement that
346 caused the problem. Most often, it will be a single line of code.
347 However, it might occasionally be a multiline statement that
348 includes code surrounded by some brackets spanning multiple lines.
349
350 It will set the following:
351
352 - self.statement_tokens: a list of all the tokens in the problem statement
353 - self.bad_token: the token identified as causing the problem based on offset.
354 - self.statement_brackets: a list of open brackets '([{' not yet closed
355 - self.begin_brackets: a list of open brackets '([{' in a statement
356 before the bad token.
357 - self.end_bracket: an unmatched closing bracket ')]}' signaling an error
358 - self.all_statements: list of all individual identified statements up to
359 and including the problem statement.
360 """
361
362 previous_row = -1
363 previous_token = None
364 continuation_line = False
365 # Some tokens cannot occur within brackets; if they are indicated as being
366 # the offending token, it might be because we have an unclosed bracket.
367 should_begin_statement = [
368 "assert",
369 "async",
370 "await",
371 "break",
372 "class",
373 "continue",
374 "def",
375 "del",
376 "elif",
377 "except",
378 "finally",
379 "global",
380 "import", # cannot write: from (x import ...
381 "nonlocal",
382 "pass",
383 "raise",
384 "return",
385 "try",
386 "with",
387 "while",
388 "yield",
389 ]
390
391 last_line_to_include = self.linenumber
392 for token in source_tokens:
393 if (
394 token.start_row > last_line_to_include
395 and not continuation_line
396 and not self.statement_brackets
397 ):
398 break
399
400 # is this a new statement?
401 # Valid statements will have matching brackets (), {}, [].
402 # A new statement will typically start on a new line and will be
403 # preceded by valid statements.
404
405 # An initial version was based on the assumption that any semicolon
406 # would be used correctly and would indicate the end of a statement;
407 # however, I am guessing that it more likely indicates
408 # a typo, and that the user wanted to write a comma or a colon, so I
409 # do not treat them in any special way.
410 if token.is_unclosed_string():
411 token.string = token.string.rstrip()
412 self.statement_tokens.append(token)
413 self.linenumber = token.start_row
414 break
415 if token.start_row > previous_row:
416 if previous_token is not None:
417 continuation_line = previous_token.line.endswith("\\\n")
418 if (
419 token.start_row <= last_line_to_include
420 and not self.statement_brackets
421 ):
422 if self.statement_tokens:
423 self.all_statements.append(self.statement_tokens[:])
424 self.statement_tokens = []
425 self.begin_brackets = []
426 if token.start_row > last_line_to_include and self.statement_brackets:
427 # The statement continues beyond the line with the error, so
428 # we make sure to include this additional line.
429 last_line_to_include = token.start_row
430 previous_row = token.start_row
431
432 self.statement_tokens.append(token)
433 # The offset seems to be different depending on Python versions,
434 # sometimes matching the beginning of a token, sometimes the end.
435 # Furthermore, the end of a token (end_col) might be equal to
436 # the beginning of the next (start_col).
437 # Additionally, for Python 3.10, multiple tokens can be highlighted
438 # if they are on the same line.
439 if self.highlighted_tokens: # not None and not empty list
440 if (
441 self.linenumber == token.start_row
442 and self.end_offset is not None
443 and (
444 self.offset < token.end_col < self.end_offset
445 or self.end_offset == 0
446 )
447 and token.string.strip()
448 ):
449 self.highlighted_tokens.append(token)
450 elif (
451 token.start_row == last_line_to_include
452 and token.start_col <= self.offset <= token.end_col
453 and self.bad_token is None
454 and token.string.strip()
455 ):
456 self.bad_token = token
457 if self.bad_token.is_comment():
458 self.bad_token_comment = self.bad_token
459 self.bad_token = self.prev_token
460 if self.highlighted_tokens is not None:
461 self.highlighted_tokens.append(self.bad_token)
462 elif (
463 token.string.strip()
464 and not token.is_comment()
465 and self.bad_token is None
466 ):
467 self.prev_token = token
468
469 previous_token = token
470
471 if (
472 self.bad_token in should_begin_statement
473 and self.bad_token != self.statement_tokens[0]
474 and self.statement_brackets
475 ):
476 break # we almost certainly have an unclosed bracket
477 # Note: '' in 'any string' == True
478 # careful to not accidentally include null strings as brackets
479 if not token.string or token.string not in "()[]}{":
480 continue
481
482 if token.string in "([{":
483 self.statement_brackets.append(token.string)
484 if self.bad_token is None or self.bad_token is token:
485 self.begin_brackets.append(token)
486 elif token.string in ")]}":
487 self.end_bracket = token
488 if not self.statement_brackets:
489 break
490
491 open_bracket = self.statement_brackets.pop()
492 if not matching_brackets(open_bracket, token.string):
493 self.statement_brackets.append(open_bracket)
494 break
495 if self.begin_brackets and self.bad_token is None:
496 self.begin_brackets.pop()
497 self.end_bracket = None
498
499 if self.statement_tokens: # Protecting against EOF while parsing
500 last_line = token_utils.untokenize(self.statement_tokens)
501 if last_line.strip():
502 self.all_statements.append(self.statement_tokens)
503 elif self.all_statements:
504 self.statement_tokens = self.all_statements[-1]
505
506 def remove_meaningless_tokens(self):
507 """Given a list of tokens, remove all space-like tokens and comments;
508 also assign the index value of the bad token.
509 """
510 index = 0
511 tokens = []
512 for tok in self.statement_tokens:
513 if not tok.string.strip() or tok.is_comment():
514 continue
515 tokens.append(tok)
516 if tok is self.bad_token:
517 self.bad_token_index = index
518 index += 1
519 return tokens
520
521
522 def get_lines_from_statement(tokens, linenumber, prev_token):
523 lines = []
524 end_docstring = False
525 for token in tokens:
526 current_linenumber = token.start_row
527 current_line = token.line.rstrip()
528 if lines and prev_token.end_row == current_linenumber:
529 continue
530 if linenumber < current_linenumber and token == tokens[0]:
531 break
532 if linenumber - current_linenumber < 5:
533 if end_docstring == current_line:
534 end_docstring = False
535 continue
536 if "\n" in current_line:
537 text = current_line.split("\n") # handle docstring
538 for line in text:
539 lines.append((current_linenumber, line))
540 current_linenumber += 1
541 end_docstring = text[-1]
542 current_linenumber -= 1
543 else:
544 lines.append((current_linenumber, current_line))
545 else:
546 if "\n" in current_line:
547 text = current_line.split("\n")
548 end_docstring = text[-1]
549 prev_token = token
550 return lines