Debian Codegraph @

friendly_traceback/syntax_errors/statement_analyzer.py

raw symbols SCIP
1 # type: ignore
2 """This module contains functions that are used to
3 analyze a single statement which has been identified
4 as containing a syntax error with the message "invalid syntax".
5 """
6 import keyword
7 import sys
8
9 from .. import debug_helper, token_utils, utils
10 from ..ft_gettext import current_lang, internal_error
11 from . import error_in_def, fixers
12 from . import syntax_utils as su
13
14 STATEMENT_ANALYZERS = []
15 _ = current_lang.translate
16
17
18 def more_errors():
19
20 return "\n" + _(
21 "However, making such a change would still not correct\n"
22 "all the syntax errors in the code you wrote.\n"
23 )
24
25
26 def _possibly_inside_dict(statement):
27 if statement.statement_brackets:
28 return False
29 for bracket in reversed(statement.begin_brackets):
30 if bracket == "{":
31 break
32 else:
33 return False
34 between_brackets = False
35 found_colon = False
36 for token in statement.tokens:
37 if token == bracket:
38 between_brackets = True
39 if between_brackets:
40 if token == ":":
41 found_colon = True
42 elif token.is_keyword():
43 return False
44 if token == "}":
45 return found_colon
46 return False
47
48
49 def add_statement_analyzer(func):
50 """A simple decorator that adds a function to the list
51 of all functions that analyze a single statement."""
52 STATEMENT_ANALYZERS.append(func)
53
54 # The following is needed if we wish to call explicitly
55 # one of the functions below from another file.
56 # We sometimes do this for consistency when later version of
57 # Python give us a specific message instead of just 'invalid syntax'.
58 def wrapper(statement):
59 return func(statement)
60
61 return wrapper
62
63
64 # ========================================================
65 # Main calling function
66 # ========================================================
67
68
69 def analyze_statement(statement):
70 """Analyzes the statement as identified by Python as that
71 on which the error occurred."""
72 if not statement.tokens: # pragma: no cover
73 debug_helper.log("Statement with no tokens in statement_analyser.py")
74 return {"cause": internal_error(Exception("No tokens"))}
75
76 if statement.first_token == "def" or (
77 statement.first_token == "async" and statement.tokens[1] == "def"
78 ):
79 cause = error_in_def.analyze_def_statement(statement)
80 if cause:
81 return cause
82
83 for analyzer in STATEMENT_ANALYZERS:
84 cause = analyzer(statement)
85 if cause:
86 return cause
87 return {}
88
89
90 # ==================
91 # IMPORTANT: causes are looked at in the same order as they appear below.
92 # Changing the order could possibly yield incorrect results
93 # ==================
94
95
96 @add_statement_analyzer
97 def invalid_non_printable_character(statement=None):
98 char = statement.bad_token.string
99 if len(char) == 1 and token_utils.is_invisible_control_character(char) == char:
100 return {
101 "cause": _(
102 "Your code contains the invalid non-printable character {char}.\n"
103 ).format(char=repr(char))
104 }
105 return {}
106
107
108 @add_statement_analyzer
109 def missing_index(statement=None):
110 if not (statement.bad_token == "]" and statement.prev_token == "["):
111 return {}
112 new_tokens = []
113 for tok in statement.tokens:
114 if (
115 tok is statement.bad_token
116 ): # Check for identity as other brackets might be present
117 new_tokens.append("0")
118 new_tokens.append(tok)
119
120 new_line = token_utils.untokenize(new_tokens)
121 if not fixers.check_statement(new_line):
122 return {}
123 hint = _("Did you forget to add an index?\n")
124 cause = _(
125 "It looks like you forgot to add an index.\n"
126 "Perhaps you meant to write something like:\n\n"
127 " {new_line}"
128 ).format(new_line=new_line)
129 return {"cause": cause, "suggest": hint}
130
131
132 @add_statement_analyzer
133 def mismatched_brackets(statement):
134 """Detecting code that ends with an unmatched closing bracket"""
135 if not (statement.end_bracket and statement.bad_token == statement.last_token):
136 return {}
137
138 if not statement.statement_brackets:
139 lineno = statement.end_bracket.start_row
140 source = f"\n {lineno}: {statement.source_lines[lineno - 1]}"
141 shift = len(str(lineno)) + statement.end_bracket.start_col + 6
142 source += " " * shift + "^\n"
143
144 cause = (
145 _(
146 "The closing {bracket} on line {linenumber}"
147 " does not match anything.\n"
148 ).format(
149 bracket=su.name_bracket(statement.end_bracket),
150 linenumber=statement.end_bracket.start_row,
151 )
152 + source
153 )
154
155 return {"cause": cause}
156
157 open_bracket = statement.begin_brackets[-1]
158 open_lineno = open_bracket.start_row
159 end_bracket = statement.end_bracket
160 end_lineno = end_bracket.start_row
161
162 source = f"\n {open_lineno}: {statement.source_lines[open_lineno - 1]}"
163 shift = len(str(open_lineno)) + open_bracket.start_col + 6
164 statement.location_markers = {}
165 if open_lineno == end_lineno:
166 source += " " * shift + "^"
167 statement.location_markers[open_lineno] = " " * open_bracket.start_col + "^"
168 shift = end_bracket.start_col - open_bracket.start_col - 1
169 source += " " * shift + "^\n"
170 statement.location_markers[open_lineno] += " " * shift + "^"
171 else:
172 source += " " * shift + "^\n"
173 statement.location_markers[open_lineno] = " " * open_bracket.start_col + "^"
174 source += f" {end_lineno}: {statement.source_lines[end_lineno - 1]}"
175 shift = len(str(end_lineno)) + end_bracket.start_col + 6
176 source += " " * shift + "^\n"
177 statement.location_markers[end_lineno] = " " * end_bracket.start_col + "^"
178
179 cause = (
180 _(
181 "The closing {bracket} on line {close_lineno} does not match "
182 "the opening {open_bracket} on line {open_lineno}.\n"
183 ).format(
184 bracket=su.name_bracket(statement.end_bracket),
185 close_lineno=statement.end_bracket.start_row,
186 open_bracket=su.name_bracket(open_bracket),
187 open_lineno=open_bracket.start_row,
188 )
189 + source
190 )
191 return {"cause": cause}
192
193
194 @add_statement_analyzer
195 def copy_pasted_code(statement):
196 """Detecting code that starts with a Python prompt"""
197 first_token = statement.first_token
198 if first_token not in [">>", "..."]:
199 return {}
200
201 if statement.bad_line.strip() == "....":
202 hint = _("Did you mean to write `...`?\n")
203 cause = _(
204 "It looks like you meant to write `...` but added an extra `.` by mistake.\n"
205 )
206 return {"cause": cause, "suggest": hint}
207
208 hint = _("Did you use copy-paste?\n")
209 if (
210 first_token == ">>"
211 and first_token == statement.bad_token
212 and statement.next_token == ">"
213 ):
214 statement.location_markers = su.highlight_two_tokens(
215 first_token, statement.next_token
216 )
217 cause = _(
218 "It looks like you copy-pasted code from an interactive interpreter.\n"
219 "The Python prompt, `>>>`, should not be included in your code.\n"
220 )
221 return {"cause": cause, "suggest": hint}
222 elif (
223 statement.first_token == statement.bad_token
224 or statement.prev_token == statement.first_token
225 ):
226 statement.location_markers = su.highlight_single_token(statement.first_token)
227 cause = _(
228 "It looks like you copy-pasted code from an interactive interpreter.\n"
229 "The Python prompt, `...`, should not be included in your code.\n"
230 )
231 return {"cause": cause, "suggest": hint}
232 return {} # pragma: no cover
233
234
235 @add_statement_analyzer
236 def detect_backquote(statement):
237 """Detecting if the error is due to using `x` which was allowed
238 in Python 2.
239 """
240 if statement.bad_token == "`":
241 hint = _("You should not use the backquote character.\n")
242 cause = _(
243 "You are using the backquote character.\n"
244 "Either you meant to write a single quote, ', "
245 "or copied Python 2 code;\n"
246 "in this latter case, use the function `repr(x)`."
247 )
248 return {"cause": cause, "suggest": hint}
249 return {}
250
251
252 @add_statement_analyzer
253 def wrong_code_block(statement):
254 if not (
255 statement.bad_token == ":"
256 and statement.nb_tokens == 2
257 and statement.prev_token.string in ("if", "for", "while", "class")
258 ):
259 return {}
260
261 word = statement.prev_token.string
262 if word in ("if", "while"):
263 hint = _("You forgot to add a condition.\n")
264 if word == "if":
265 cause = _(
266 "An `if` statement requires a condition:\n\n"
267 " if condition:\n"
268 " ...\n\n"
269 )
270 else:
271 cause = _(
272 "A `while` loop requires a condition:\n\n"
273 " while condition:\n"
274 " ...\n\n"
275 )
276 elif word == "for":
277 hint = _("A `for` loop requires at least 3 more terms.\n")
278 cause = _(
279 "A `for` loop is an iteration over a sequence:\n\n"
280 " for element in sequence:\n"
281 " ...\n\n"
282 )
283 else:
284 hint = _("A class needs a name.\n")
285 cause = _(
286 "A `class` statement requires a name:\n\n"
287 " class SomeName:\n"
288 " ...\n\n"
289 )
290
291 return {"cause": cause, "suggest": hint}
292
293
294 @add_statement_analyzer
295 def keyword_as_attribute(statement):
296 """Will identify something like obj.True ..."""
297 if statement.prev_token != ".":
298 return {}
299
300 word = statement.bad_token
301 if word.is_keyword():
302 cause = _(
303 "You cannot use the Python keyword `{word}` as an attribute.\n\n"
304 ).format(word=word)
305 else:
306 return {}
307
308 hint = _("`{word}` cannot be used as an attribute.\n").format(word=word)
309 return {"cause": cause, "suggest": hint}
310
311
312 @add_statement_analyzer
313 def confused_elif(statement):
314 name = None
315 # skipcq: PYL-R1714
316 if statement.bad_token == "elseif" or statement.prev_token == "elseif":
317 name = "elseif"
318 if statement.first_token == "elseif":
319 statement.location_markers = su.highlight_single_token(
320 statement.first_token
321 )
322 else:
323 debug_helper.log("problem in confused_elif")
324 elif statement.bad_token == "if" and statement.prev_token == "else":
325 name = "else if"
326 statement.location_markers = su.highlight_two_tokens(
327 statement.prev_token, statement.bad_token, between="^"
328 )
329 if name:
330 hint = _("Perhaps you meant to write `elif`.\n")
331 cause = _(
332 "You likely meant to use Python's `elif` keyword\n"
333 "but wrote `{name}` instead.\n"
334 "\n"
335 ).format(name=name)
336 return {"cause": cause, "suggest": hint}
337 return {}
338
339
340 @add_statement_analyzer
341 def import_from(statement):
342 if statement.bad_token != "from" or statement.tokens[0] != "import":
343 return {}
344
345 statement.location_markers = su.highlight_two_tokens(
346 statement.tokens[0], statement.bad_token
347 )
348 bad_line = statement.bad_line.replace("import ", "").strip()
349 function, module = bad_line.split(" from ")
350 new_line = f"from {module} import {function}"
351 if not fixers.check_statement(new_line):
352 function = module = "(...)"
353
354 hint = _("Did you mean `from {module} import {function}`?\n").format(
355 module=module.strip(), function=function.strip()
356 )
357 cause = _(
358 "You wrote something like\n\n"
359 " import {function} from {module}\n\n"
360 "instead of\n\n"
361 " from {module} import {function}\n\n"
362 ).format(module=module.strip(), function=function.strip())
363 return {"cause": cause, "suggest": hint}
364
365
366 @add_statement_analyzer
367 def misplaced_quote(statement):
368 """This looks for a single misplaced quote, something like
369 info = 'I don't mind.'
370
371 The clue we are looking for is a STRING token ('don')
372 followed by something else than a string.
373 """
374 if not statement.prev_token.is_string():
375 return {}
376
377 # Create a new line escaping an inner quote for the entire line.
378 new_tokens = []
379 for tok in statement.tokens:
380 if tok == statement.prev_token:
381 s = tok.string[:-1] + tok.string[-1].replace("'", "\\'").replace('"', '\\"')
382 tok_copy = statement.prev_token.copy()
383 tok_copy.string = s
384 new_tokens.append(tok_copy)
385 else:
386 new_tokens.append(tok)
387
388 new_line = token_utils.untokenize(new_tokens)
389 if not fixers.check_statement(new_line):
390 return {}
391
392 quote_position = statement.prev_token.end_col
393 indent = len(statement.bad_line) - len(statement.bad_line.lstrip())
394 quote_position -= indent
395 mark = " " * (quote_position - 1) + "^^"
396
397 hint = _("Perhaps you forgot to escape a quote character.\n")
398 cause = _(
399 "I suspect that you were trying to use a quote character inside a string\n"
400 "that was enclosed in quotes of the same kind.\n"
401 "Perhaps you should have escaped the inner quote character:\n\n"
402 " {new_line}\n"
403 " {mark}\n"
404 ).format(new_line=new_line, mark=mark)
405 return {"cause": cause, "suggest": hint}
406
407
408 @add_statement_analyzer
409 def detect_walrus(statement):
410 """Detecting if code uses named assignment operator := with an
411 older version of Python.
412 """
413 if sys.version_info >= (3, 8):
414 return {}
415
416 # Normally, the token identified as the bad token should be
417 # '='; however, in some test cases where a named assignment
418 # is not allowed, it is ':' that is identified as the
419 # bad token.
420
421 bad = statement.bad_token
422 prev = statement.prev_token
423 next_token = statement.next_token
424
425 if (prev == ":" and bad == "=" and bad.immediately_after(prev)) or (
426 bad == ":" and next_token == "=" and bad.immediately_before(next_token)
427 ):
428 hint = _(
429 "The augmented assignment operator is not allowed in Python version {version}.\n"
430 ).format(version=f"{sys.version_info.major}.{sys.version_info.minor}")
431 cause = _(
432 "You appear to be using the operator `:=`, sometimes called\n"
433 "the walrus operator. This operator requires the use of\n"
434 "Python 3.8 or newer. You are using version {version}.\n"
435 ).format(version=f"{sys.version_info.major}.{sys.version_info.minor}")
436 return {"cause": cause, "suggest": hint}
437
438 return {}
439
440
441 @add_statement_analyzer
442 def inverted_operators(statement):
443 """Detect if operators might have been inverted"""
444 is_op = token_utils.is_operator
445 if not is_op(statement.bad_token):
446 return {}
447
448 prev = statement.prev_token
449 bad = statement.bad_token
450 next_ = statement.next_token
451
452 if is_op(prev) and is_op(bad.string + prev.string) and prev.immediately_before(bad):
453 first = prev
454 second = bad
455 elif (
456 is_op(next_)
457 and is_op(next_.string + bad.string)
458 and bad.immediately_before(next_)
459 ): # pragma: no cover
460 # I cannot think of a situation where Python would highlight the first
461 # of two consecutive operators as being the incorrect one.
462 debug_helper.log("inverted_operators: new case")
463 first = bad
464 second = next_
465 else:
466 return {}
467
468 # Before we make any attempt at modifying the original code,
469 # we make sure that our statement checker can properly identify that
470 # the original code is invalid. See #205
471 if fixers.check_statement(statement.bad_line):
472 return {}
473
474 correct = second.string + first.string
475 hint = _("Did you write operators in an incorrect order?\n")
476 cause = _(
477 "It looks like you wrote two operators (`{first}` and `{second}`)\n"
478 "in the wrong order: `{wrong}` instead of `{correct}`.\n"
479 ).format(
480 first=first.string,
481 second=second.string,
482 correct=correct,
483 wrong=first.string + second.string,
484 )
485 statement.location_markers = su.highlight_two_tokens(first, second)
486
487 new_statement = fixers.replace_two_tokens(
488 statement.statement_tokens,
489 first,
490 first_string=correct,
491 second_token=second,
492 second_string="",
493 )
494 if fixers.check_statement(new_statement):
495 return {"cause": cause, "suggest": hint}
496
497 return {"cause": cause + more_errors(), "suggest": hint}
498
499
500 @add_statement_analyzer
501 def consecutive_operators(statement):
502 is_op = token_utils.is_operator
503
504 if not (is_op(statement.bad_token) and is_op(statement.prev_token)):
505 return {}
506
507 statement.location_markers = su.highlight_two_tokens(
508 statement.prev_token, statement.bad_token
509 )
510
511 if statement.bad_token == "=" and statement.prev_token == "==":
512 cause = _(
513 "You wrote three equal signs in a row which is allowed in some\n"
514 "programming languages, but not in Python. To check if two objects\n"
515 "are equal, use two equal signs, `==`; to see if two names represent\n"
516 "the exact same object, use the operator `is`.\n"
517 )
518 hint = _("Did you mean to use `is` instead of `===`?\n")
519 return {"cause": cause, "suggest": hint}
520
521 if statement.bad_token == statement.prev_token:
522 cause = _(
523 "You cannot have write the same operator, `{op}`, twice in a row.\n"
524 "Perhaps you wrote one of them by mistake\n"
525 "or forgot to write something between them.\n"
526 ).format(op=statement.prev_token)
527 else:
528 if (
529 statement.prev_token == ":"
530 and statement.bad_token == "*"
531 and _possibly_inside_dict(statement)
532 ):
533 cause = _(
534 "You cannot have these two operators, `{first}` and `{second}`,\n"
535 "following each other.\n"
536 "It looks like you tried to use a starred expression as a dict value;\n"
537 "this is not allowed.\n"
538 ).format(first=statement.prev_token, second=statement.bad_token)
539 new_statement = fixers.replace_token(
540 statement.statement_tokens, statement.bad_token, ""
541 )
542 # See issue 205
543 if fixers.check_statement(new_statement) and not fixers.check_statement(
544 statement.bad_line
545 ):
546 cause += "\n" + _(
547 "The following statement has no syntax error:\n\n {statement}\n"
548 ).format(statement=new_statement)
549 return {"cause": cause}
550 cause = _(
551 "You cannot have these two operators, `{first}` and `{second}`,\n"
552 "following each other. Perhaps you wrote one of them by mistake\n"
553 "or forgot to write something between them.\n"
554 ).format(first=statement.prev_token, second=statement.bad_token)
555
556 if is_op(statement.prev_token.string + statement.bad_token.string):
557 cause += _(
558 "Or perhaps you included a space by mistake between the two operators\n"
559 "and meant to write `{oper}` as a single operator.\n"
560 ).format(oper=statement.prev_token.string + statement.bad_token.string)
561 return {"cause": cause}
562
563
564 def _walrus_instead_of_equal_39(statement):
565 # Python version 3.9 identifies a token beyond :=
566 for tok in statement.statement_tokens[: statement.bad_token_index + 1]:
567 if tok == ":=":
568 return tok
569 return None
570
571
572 @add_statement_analyzer
573 def walrus_instead_of_equal(statement):
574 # TODO: check this
575 if (3, 8) < sys.version_info < (3, 10):
576 bad_token = _walrus_instead_of_equal_39(statement)
577 if bad_token is None:
578 return {}
579 elif statement.bad_token != ":=":
580 return {}
581 else:
582 bad_token = statement.bad_token
583
584 # Before we make any attempt at modifying the original code,
585 # we make sure that our statement checker can properly identify that
586 # the original code is invalid. See #205
587 if fixers.check_statement(statement.bad_line):
588 return {}
589
590 new_statement = fixers.replace_token(statement.statement_tokens, bad_token, "=")
591 if fixers.check_statement(new_statement):
592 hint = _("Did you mean to use `=`?\n")
593 cause = _(
594 "You use the augmented assignment operator `:=` where\n"
595 "the normal assignment operator `=` was required.\n"
596 )
597 return {"cause": cause, "suggest": hint}
598 return {}
599
600
601 @add_statement_analyzer
602 def assign_instead_of_equal(statement):
603 """Checks to see if an assignment sign, '=', has been used instead of
604 an equal sign, '==', in an if, elif or while statement."""
605 if statement.filename == "<fstring>":
606 return {}
607 if statement.highlighted_tokens: # Python 3.10
608 bad_token = statement.next_token
609 else:
610 bad_token = statement.bad_token
611
612 if bad_token != "=":
613 return {}
614
615 # Before we make any attempt at modifying the original code,
616 # we make sure that our statement checker can properly identify that
617 # the original code is invalid. See #205
618 if fixers.check_statement(statement.bad_line):
619 return {}
620
621 new_statement = fixers.replace_token(statement.statement_tokens, bad_token, "==")
622 if not fixers.check_statement(new_statement):
623 return {}
624
625 new_statement = fixers.replace_token(statement.statement_tokens, bad_token, ":=")
626 walrus = fixers.check_statement(new_statement)
627
628 if not walrus:
629 hint = _("Perhaps you needed `==` instead of `=`.\n")
630 cause = _(
631 "You likely used an assignment operator `=` instead of an equality operator `==`.\n"
632 )
633 for tok in statement.tokens[statement.bad_token_index :]:
634 if tok == "=":
635 new_statement = fixers.replace_token(
636 statement.statement_tokens, tok, "=="
637 )
638 if fixers.check_statement(new_statement):
639 cause += _(
640 "The following statement would not contain a syntax error:\n\n"
641 " {new_statement}"
642 ).format(new_statement=new_statement)
643 return {"cause": cause, "suggest": hint}
644
645 hint = _("Perhaps you needed `==` or `:=` instead of `=`.\n")
646 cause = _(
647 "You used an assignment operator `=`; perhaps you meant to use \n"
648 "an equality operator, `==`, or the walrus operator `:=`.\n"
649 )
650 return {"cause": cause, "suggest": hint}
651
652
653 @add_statement_analyzer
654 def print_as_statement(statement):
655 # example: print len('hello')
656 if not (
657 ( # Python 3.10+
658 statement.bad_token == statement.first_token == "print"
659 and statement.highlighted_tokens is not None
660 )
661 or ( # Python < 3.10
662 statement.prev_token == statement.first_token == "print"
663 and statement.bad_token != "("
664 )
665 ):
666 return {}
667 # Before we make any attempt at modifying the original code,
668 # we make sure that our statement checker can properly identify that
669 # the original code is invalid. See #205
670 if fixers.check_statement(statement.bad_line):
671 return {}
672
673 content = statement.entire_statement.replace("print", "", 1).strip()
674 possible_statement = f"print({content})"
675 valid = fixers.check_statement(possible_statement)
676 if "\n" in content or len(content) > 40 or not valid:
677 message = "..."
678 else:
679 message = content
680 cause = _(
681 "Perhaps you need to type\n\n"
682 " print({message})\n\n"
683 "In older version of Python, `print` was a keyword.\n"
684 "Now, `print` is a function; you need to use parentheses to call it.\n"
685 ).format(message=message)
686 if not valid:
687 cause += _("Note that arguments of `print` must be separated by commas.\n")
688 hint = _("Did you mean `print({message})`?\n").format(message=message)
689 return {"cause": cause, "suggest": hint}
690
691
692 @add_statement_analyzer
693 def calling_python_or_pip(statement):
694 if statement.first_token.string not in ("pip", "python", "python3"):
695 return {}
696 # A single token statement with 'python' or 'pip' should not have
697 # caused a SyntaxError
698 second = statement.tokens[1]
699 # python followed by an operator is likely a valid statement.
700 # One exception is something like python -im friendly :)
701 if second.is_operator() and second != "-":
702 return {}
703
704 cause = _(
705 "It looks as if you are attempting to use pip to install a module.\n"
706 "`pip` is a command that needs to run in a terminal,\n"
707 "not from a Python interpreter.\n"
708 )
709
710 for tok in statement.tokens:
711 if tok == "pip":
712 hint = _("Pip cannot be used in a Python interpreter.\n")
713 return {"cause": cause, "suggest": hint}
714
715 cause = _(
716 "I am guessing that you are attempting to use Python to run a program.\n"
717 "You must do so from a terminal and not from a Python interpreter.\n"
718 )
719 return {"cause": cause}
720
721
722 @add_statement_analyzer
723 def dot_followed_by_bracket(statement):
724 if statement.bad_token.string in "()[]{}" and statement.prev_token == ".":
725 cause = _("You cannot have a dot `.` followed by `{bracket}`.\n").format(
726 bracket=statement.bad_token
727 )
728 else:
729 return {}
730
731 # Before we make any attempt at modifying the original code,
732 # we make sure that our statement checker can properly identify that
733 # the original code is invalid. See #205
734 if fixers.check_statement(statement.bad_line):
735 return {}
736
737 new_statement = fixers.replace_token(
738 statement.statement_tokens, statement.prev_token, ","
739 )
740 if fixers.check_statement(new_statement):
741 cause += _("Perhaps you need to replace the dot by a comma.\n")
742
743 return {"cause": cause}
744
745
746 @add_statement_analyzer
747 def raise_single_exception(statement):
748 if statement.first_token != "raise":
749 return {}
750
751 if statement.bad_token == "," and statement.prev_token.is_identifier():
752 cause = _(
753 "It looks like you are trying to raise an exception using Python 2 syntax.\n"
754 )
755 return {"cause": cause}
756 return {}
757
758
759 @add_statement_analyzer
760 def invalid_double_star_operator(statement):
761 if statement.bad_token == "**":
762 cause = _(
763 "The double star operator `**` is likely interpreted to mean that\n"
764 "dict unpacking is to be used which is not allowed or does not make sense here.\n"
765 )
766 return {"cause": cause}
767
768 return {}
769
770
771 @add_statement_analyzer
772 def missing_colon(statement):
773 """look for missing colon at the end of statement"""
774 # TODO: check all keywords listed here, with single keyword missing colon, like:
775 # if
776
777 if statement.last_token == ":" or statement.bad_token != statement.last_token:
778 return {}
779
780 name = statement.first_token
781 if name.string not in (
782 "async",
783 "class",
784 "def",
785 "if",
786 "elif",
787 "else",
788 "for",
789 "while",
790 "try",
791 "except",
792 "finally",
793 "with",
794 ):
795 return {}
796
797 # Before we make any attempt at modifying the original code,
798 # we make sure that our statement checker can properly identify that
799 # the original code is invalid. See #205
800 if fixers.check_statement(statement.bad_line):
801 return {}
802
803 new_statement = fixers.replace_token(
804 statement.statement_tokens,
805 statement.bad_token,
806 statement.bad_token.string + ":",
807 )
808 if not fixers.check_statement(new_statement):
809 return {}
810
811 name = statement.first_token
812
813 hint = _("Did you forget a colon `:`?\n")
814 statement.location_markers = su.highlight_added_token(statement.bad_token, ":")
815
816 if name.string in ("for", "while"):
817 cause = _(
818 "You wrote a `{for_while}` loop but\n"
819 "forgot to add a colon `:` at the end\n"
820 "\n"
821 ).format(for_while=name)
822 return {"cause": cause, "suggest": hint}
823
824 cause = _(
825 "You wrote a statement beginning with\n"
826 "`{name}` but forgot to add a colon `:` at the end.\n"
827 "\n"
828 ).format(name=name)
829 return {"cause": cause, "suggest": hint}
830
831
832 @add_statement_analyzer
833 def semi_colon_instead_of_comma(statement):
834 """Writing a semicolon as a typo"""
835 if statement.bad_token != ";":
836 return {}
837
838 # Before we make any attempt at modifying the original code,
839 # we make sure that our statement checker can properly identify that
840 # the original code is invalid. See #205
841 if fixers.check_statement(statement.bad_line):
842 return {}
843
844 new_statement = fixers.replace_token(
845 statement.statement_tokens, statement.bad_token, ","
846 )
847 if fixers.check_statement(new_statement):
848 cause = _("You wrote a semicolon, `;`, where a comma was expected.\n")
849 hint = _("Did you mean to write a comma?\n")
850 return {"cause": cause, "suggest": hint}
851
852 # perhaps used multiple semicolons instead of comma
853 if statement.last_token == ";":
854 new_statement = fixers.replace_token(
855 statement.statement_tokens, statement.last_token, ""
856 )
857 else:
858 new_statement = statement.entire_statement
859 while True:
860 tokens = token_utils.tokenize(new_statement)
861 for tok in tokens:
862 if tok == ";":
863 break
864 else:
865 break
866 new_statement = fixers.replace_token(tokens, tok, ",")
867 if fixers.check_statement(new_statement):
868 cause = _("You wrote semicolons, `;`, where commas were expected.\n")
869 hint = _("Did you mean to write commas?\n")
870 return {"cause": cause, "suggest": hint}
871
872 return {} # pragma: no cover
873
874
875 @add_statement_analyzer
876 def semi_colon_instead_of_colon(statement):
877 """Writing a semicolon as a typo"""
878 if statement.bad_token != ";":
879 return {}
880 # Before we make any attempt at modifying the original code,
881 # we make sure that our statement checker can properly identify that
882 # the original code is invalid. See #205
883 if fixers.check_statement(statement.bad_line):
884 return {}
885 new_statement = fixers.replace_token(
886 statement.statement_tokens, statement.bad_token, ":"
887 )
888 if fixers.check_statement(new_statement):
889 cause = _("You wrote a semicolon, `;`, where a colon was expected.\n")
890 hint = _("Did you mean to write a colon?\n")
891 return {"cause": cause, "suggest": hint}
892
893 return {} # pragma: no cover
894
895
896 @add_statement_analyzer
897 def invalid_hexadecimal(statement):
898 """Identifies problem caused by invalid character in an hexadecimal number."""
899 if statement.highlighted_tokens: # Python 3.10
900 prev = statement.bad_token
901 wrong = statement.next_token
902 else:
903 prev = statement.prev_token
904
905 wrong = statement.bad_token
906 if not (prev.immediately_before(wrong) and prev.string.lower().startswith("0x")):
907 return {}
908
909 hint = _("Did you made a mistake in writing an hexadecimal integer?\n")
910 cause = _(
911 "It looks like you used an invalid character (`{character}`) in an hexadecimal number.\n\n"
912 "Hexadecimal numbers are base 16 integers that use the symbols `0` to `9`\n"
913 "to represent values 0 to 9, and the letters `a` to `f` (or `A` to `F`)\n"
914 "to represent values 10 to 15.\n"
915 "In Python, hexadecimal numbers start with either `0x` or `0X`,\n"
916 "followed by the characters used to represent the value of that integer.\n"
917 ).format(character=wrong.string[0])
918 return {"cause": cause, "suggest": hint}
919
920
921 @add_statement_analyzer
922 def invalid_octal(statement):
923 """Identifies problem caused by invalid character in an octal number."""
924 prev = statement.prev_token
925 wrong = statement.bad_token
926 if not (prev.immediately_before(wrong) and prev.string.lower().startswith("0o")):
927 return {}
928 bad_digit = wrong.string[0]
929
930 hint = _("Did you made a mistake in writing an octal integer?\n")
931 cause = _(
932 "It looks like you used an invalid character (`{character}`) in an octal number.\n\n"
933 "Octal numbers are base 8 integers that only use the symbols `0` to `7`\n"
934 "to represent values.\n"
935 "In Python, octal numbers start with either `0o` or `0O`,\n"
936 "(the digit zero followed by the letter `o`)\n"
937 "followed by the characters used to represent the value of that integer.\n"
938 ).format(character=bad_digit)
939 return {"cause": cause, "suggest": hint}
940
941
942 @add_statement_analyzer
943 def invalid_name(statement):
944 """Identifies invalid identifiers when a name begins with a number"""
945 first = statement.prev_token
946 second = statement.bad_token
947 # New in Python 3.10
948 if (
949 statement.highlighted_tokens is not None
950 and len(statement.highlighted_tokens) > 1
951 ):
952 first = statement.highlighted_tokens[0]
953 second = statement.highlighted_tokens[1]
954
955 if not (first.is_number() and second.is_name() and first.end == second.start):
956 return {}
957
958 cause = _("Valid names cannot begin with a number.\n")
959 if first == statement.first_token: # statement begins with this invalid identifier
960 for token in statement.tokens:
961 if token == "=": # Trying to assign a value to an invalid name
962 return {"cause": cause, "suggest": cause}
963
964 if second == "i" and not first.is_complex():
965 hint = _("Did you mean `{number}j`?\n").format(number=first)
966 cause = _(
967 "Perhaps you thought that `i` could be used to represent\n"
968 "the square root of `-1`. In Python, the symbol used for this is `j`\n"
969 "and the complex part is written as `some_number` immediately\n"
970 "followed by `j`, with no spaces in between.\n"
971 "Perhaps you meant to write `{number}j`.\n"
972 ).format(number=first)
973 return {"cause": cause, "suggest": hint}
974
975 if second.string in ["e", "E"] and not first.is_complex():
976 hint = _("Did you mean `{number}{second}0`?\n").format(
977 number=first, second=second
978 )
979 cause = _(
980 "Perhaps you meant to write `{number}{second}0` in scientific notation\n"
981 "and forgot the numerical value for the exponent.\n"
982 ).format(number=first, second=second)
983 return {"cause": hint + cause, "suggest": hint}
984
985 if first.is_complex():
986 note = _(
987 "[Note: `{first} * {second}` would also be valid\n"
988 "since `{first}` is a complex number.]\n"
989 ).format(first=first, second=second)
990 # Do not modify the token themselves; reuse names and create pure strings
991 # otherwise the location shown by where() will be incorrect.
992 second = first.string[-1] + second.string
993 first = first.string[:-1]
994 else:
995 note = ""
996
997 hint = _(
998 "Perhaps you forgot a multiplication operator, `{first} * {second}`.\n"
999 ).format(first=first, second=second)
1000
1001 return {"cause": cause + hint + "\n" + note, "suggest": hint}
1002
1003
1004 @add_statement_analyzer
1005 def debug_fstring(statement):
1006 """Detect debug feature of f-string introduced in Python 3.8"""
1007 if sys.version_info >= (3, 8) or not statement.fstring_error:
1008 return {}
1009
1010 if statement.bad_token == "=" and statement.prev_token.is_identifier():
1011 if statement.next_token == ")":
1012 hint = _("Your Python version does not support this f-string feature.\n")
1013 cause = _(
1014 "You are likely using a 'debug' syntax of f-strings introduced\n"
1015 "in Python version 3.8. You are using version {version}.\n"
1016 ).format(version=f"{sys.version_info.major}.{sys.version_info.minor}")
1017 return {"cause": cause, "suggest": hint}
1018
1019 cause = _(
1020 "You are likely trying to assign a value within an f-string.\n"
1021 "This is not allowed.\n"
1022 )
1023 return {"cause": cause}
1024
1025 return {} # pragma: no cover
1026
1027
1028 @add_statement_analyzer
1029 def general_fstring_problem(statement): # pragma: no cover
1030 # General f-string problems are outside of our main priorities.
1031 if not statement.fstring_error:
1032 return {}
1033
1034 cause = _(
1035 "The content of your f-string is invalid. Please consult the documentation:\n"
1036 "https://docs.python.org/3/reference/lexical_analysis.html#f-strings\n"
1037 )
1038 return {"cause": cause}
1039
1040
1041 @add_statement_analyzer
1042 def assign_to_a_keyword(statement):
1043 """Checks to see if line is of the form 'keyword = ...'"""
1044 hint = _("Python keywords cannot be used as identifiers (variable names).\n")
1045 possible_cause = _(
1046 "You were trying to assign a value to the Python keyword `{keyword}`.\n"
1047 "This is not allowed.\n"
1048 "\n"
1049 )
1050 if statement.bad_token == "=" and statement.prev_token.is_keyword():
1051 cause = possible_cause.format(keyword=statement.prev_token)
1052 bad_token = statement.prev_token
1053 elif statement.bad_token.is_keyword() and statement.next_token == "=":
1054 bad_token = statement.bad_token
1055 cause = possible_cause.format(keyword=statement.bad_token)
1056 else:
1057 return {}
1058 statement.location_markers = su.highlight_single_token(bad_token)
1059 return {"cause": cause, "suggest": hint}
1060
1061
1062 @add_statement_analyzer
1063 def lambda_with_paren(statement):
1064 if statement.bad_token != "(":
1065 return {}
1066
1067 if statement.prev_token == "lambda":
1068 cause = _(
1069 "`lambda` does not allow parentheses around its arguments.\n"
1070 "This was allowed in Python 2 but it not allowed in Python 3.\n"
1071 )
1072 return {"cause": cause}
1073
1074 tokens = list(statement.tokens[: statement.bad_token_index])
1075 tokens.reverse()
1076 for tok in tokens:
1077 if tok == "lambda":
1078 break
1079
1080 if tok.is_identifier() or tok == ",":
1081 continue
1082
1083 return {} # pragma: no cover
1084
1085 cause = _(
1086 "You cannot have explicit tuples as arguments.\n"
1087 "Assign any tuple to a parameter and unpack it\n"
1088 "within the body of the function.\n"
1089 )
1090 return {"cause": cause}
1091
1092
1093 @add_statement_analyzer
1094 def wrong_type_declaration(statement):
1095 if statement.highlighted_tokens and len(statement.highlighted_tokens) > 1:
1096 bad_token = statement.next_token
1097 prev_token = statement.bad_token
1098 else:
1099 bad_token = statement.bad_token
1100 prev_token = statement.prev_token
1101
1102 if not bad_token.is_identifier():
1103 return {}
1104 if prev_token.string not in (
1105 "int",
1106 "float",
1107 "double",
1108 "var",
1109 "let",
1110 "str",
1111 "string",
1112 "complex",
1113 ):
1114 return {}
1115 # Before we make any attempt at modifying the original code,
1116 # we make sure that our statement checker can properly identify that
1117 # the original code is invalid. See #205
1118 if fixers.check_statement(statement.bad_line):
1119 return {}
1120
1121 new_statement = fixers.replace_token(statement.statement_tokens, prev_token, "")
1122 if fixers.check_statement(new_statement):
1123 additional = _(
1124 "If you remove `{type_decl}`, you will have a valid Python statement.\n"
1125 )
1126 else:
1127 additional = _(
1128 "However, even if you remove `{type_decl}`, there would still be some\n"
1129 "some syntax errors.\n"
1130 )
1131
1132 hint = _("You do not need to declare variables in Python.\n")
1133 cause = _(
1134 "It looks like you were trying to declare that `{var}` was\n"
1135 "a variable using the word `{type_decl}`.\n"
1136 ).format(var=statement.bad_token, type_decl=prev_token) + additional.format(
1137 type_decl=prev_token
1138 )
1139 return {"cause": cause, "suggest": hint}
1140
1141
1142 @add_statement_analyzer
1143 def missing_comma_before_string_in_dict(statement):
1144 """Special case where keys and values in a dict are strings which are
1145 not separated by commas."""
1146
1147 # This is a bit of an unusual case as the error occurred due to
1148 # a forgotten comma two tokens before the token flagged by Python.
1149 if not (
1150 statement.begin_brackets
1151 and statement.begin_brackets[-1] == "{"
1152 and statement.bad_token == ":"
1153 and statement.prev_token.is_string()
1154 and statement.tokens[statement.bad_token_index - 1].is_string()
1155 ):
1156 return {}
1157 # Before we make any attempt at modifying the original code,
1158 # we make sure that our statement checker can properly identify that
1159 # the original code is invalid. See #205
1160 if fixers.check_statement(statement.bad_line):
1161 return {}
1162 before_prev = statement.tokens[statement.bad_token_index - 2]
1163
1164 new_statement = fixers.replace_token(
1165 statement.statement_tokens, before_prev, before_prev.string + ","
1166 )
1167 if not fixers.check_statement(new_statement):
1168 return {}
1169
1170 cause = _(
1171 "I am guessing that you forgot a comma between two strings\n"
1172 "when defining a dict.\n\n"
1173 ).format(kwd=statement.bad_token)
1174 mark = su.highlight_added_token(before_prev, ",")
1175
1176 new_statement = fixers.replace_token(
1177 statement.statement_tokens, before_prev, before_prev.string + ","
1178 )
1179 new_statement = su.add_mark_to_new_statement(
1180 statement, new_statement, mark[before_prev.start_row]
1181 )
1182 cause += "```\n" + new_statement + "\n```"
1183 hint = _("Did you forget a comma?\n")
1184
1185 return {"cause": cause, "suggest": hint}
1186
1187
1188 @add_statement_analyzer
1189 def missing_in_with_for(statement):
1190 """Whenever we have a 'for' keyword, there should be a corresponding
1191 'in' keyword. Cases where 'in' have been misspelled are taken care below.
1192 Note that 'in' could be used with 'if' and 'while' as well, but here
1193 we only consider the simplest cases.
1194 """
1195 index = statement.bad_token_index
1196 bad_token = statement.bad_token
1197 # Python 3.10 may highlight two tokens
1198 if statement.highlighted_tokens and len(statement.highlighted_tokens) > 1:
1199 index += 1
1200 bad_token = statement.next_token
1201
1202 nb_for = nb_in = 0
1203 for tok in statement.tokens[:index]:
1204 if tok == "for":
1205 nb_for += 1
1206 elif tok == "in":
1207 nb_in += 1
1208 if nb_for == 0 or nb_in >= nb_for:
1209 return {}
1210
1211 # Before we make any attempt at modifying the original code,
1212 # we make sure that our statement checker can properly identify that
1213 # the original code is invalid. See #205
1214 if fixers.check_statement(statement.bad_line):
1215 return {}
1216
1217 new_statement = fixers.replace_token(
1218 statement.statement_tokens, bad_token, f"in {bad_token.string}"
1219 )
1220
1221 if fixers.check_statement(new_statement):
1222 hint = _("Did you forget to write `in`?\n")
1223 cause = _(
1224 "It looks as though you forgot to use the keyword `in`\n"
1225 "as part of a `for` statement. Perhaps you meant:\n\n"
1226 " {new_statement}\n\n"
1227 ).format(new_statement=new_statement)
1228 return {"cause": cause, "suggest": hint}
1229 return {}
1230
1231
1232 @add_statement_analyzer
1233 def missing_parens_for_range(statement):
1234 if statement.prev_token != "range" or statement.last_token != ":":
1235 return {}
1236
1237 # Before we make any attempt at modifying the original code,
1238 # we make sure that our statement checker can properly identify that
1239 # the original code is invalid. See #205
1240 if fixers.check_statement(statement.bad_line):
1241 return {}
1242
1243 new_statement = fixers.replace_two_tokens(
1244 statement.tokens,
1245 statement.prev_token,
1246 statement.prev_token.string + "(",
1247 statement.last_token,
1248 ")" + statement.last_token.string,
1249 )
1250 if fixers.check_statement(new_statement):
1251 hint = _("Did you forget to write parenthesis?\n")
1252 cause = _(
1253 "It looks as though you forgot to use to use parenthesis with `range`.\n"
1254 "Perhaps you meant:\n\n"
1255 " {new_statement}\n\n"
1256 ).format(new_statement=new_statement)
1257 return {"cause": cause, "suggest": hint}
1258 return {}
1259
1260
1261 def _perhaps_misspelled_keyword(tokens, wrong):
1262 kwlist = list(keyword.kwlist)
1263 if wrong in kwlist:
1264 kwlist.remove(wrong)
1265 similar = utils.get_similar_words(wrong.string, kwlist)
1266 if not similar:
1267 return []
1268
1269 results = []
1270 for word in similar:
1271 new_statement = fixers.replace_token(tokens, wrong, word)
1272 if fixers.check_statement(new_statement):
1273 results.append((word, new_statement))
1274 return results
1275
1276
1277 def misspelled_python_keyword(tokens, bad_token):
1278 results = _perhaps_misspelled_keyword(tokens, bad_token)
1279 if not results:
1280 return {}
1281
1282 word, line = results[0]
1283 hint = _("Did you mean `{line}`?\n").format(line=line)
1284 cause = _(
1285 "Perhaps you meant to write `{keyword}` and made a typo.\n"
1286 "The correct line might be `{line}`\n"
1287 ).format(keyword=word, line=line)
1288
1289 return {"cause": cause, "suggest": hint}
1290
1291
1292 @add_statement_analyzer
1293 def comprehension_condition_or_tuple(statement):
1294 if not statement.begin_brackets:
1295 return {}
1296
1297 cause_condition = _(
1298 "I am guessing that you were writing a comprehension or a generator expression\n"
1299 "and use the wrong order for a condition.\n"
1300 "The correct order depends if there is an `else` clause or not.\n"
1301 "For example, the correct order for a list comprehensions with\n"
1302 "condition can be either\n\n"
1303 " [f(x) if condition else other for x in sequence] # 'if' before 'for'\n\n"
1304 "or, if there is no `else`\n\n"
1305 " [f(x) for x in sequence if condition] # 'if' after 'for'\n\n"
1306 )
1307
1308 cause_tuple = _(
1309 "I am guessing that you were writing a comprehension or a generator expression\n"
1310 "and forgot to include parentheses around tuples.\n"
1311 "As an example, instead of writing\n\n"
1312 " [i, i**2 for i in range(10)]\n\n"
1313 "you would need to write\n\n"
1314 " [(i, i**2) for i in range(10)]\n\n"
1315 )
1316
1317 if statement.bad_token == "else":
1318 for tok in statement.tokens[: statement.bad_token_index]:
1319 if tok == "for":
1320 cause = cause_condition
1321 break
1322 else:
1323 return {}
1324 elif statement.bad_token == "for":
1325 for tok in statement.tokens[0 : statement.bad_token_index]:
1326 if tok == "if":
1327 cause = cause_condition
1328 break
1329 else:
1330 found_bracket = False
1331 for tok in statement.tokens[0 : statement.bad_token_index]:
1332 if tok.string in "([{":
1333 found_bracket = True
1334 if tok == "," and found_bracket:
1335 cause = cause_tuple
1336 hint = _("Did you forget parentheses?\n")
1337 return {"cause": cause, "suggest": hint}
1338 return {}
1339 else:
1340 return {}
1341
1342 return {"cause": cause}
1343
1344
1345 @add_statement_analyzer
1346 def parens_around_exceptions(statement):
1347 # keep in sync with message_analyzer.parens_around_exceptions
1348 if statement.bad_token != "," or statement.first_token != "except":
1349 return {}
1350
1351 for tok in statement.tokens[1 : statement.bad_token_index]:
1352 if not tok.is_identifier() and tok != ",":
1353 return {}
1354
1355 hint = _("Did you forget parentheses?\n")
1356 cause = _(
1357 "I am guessing that you wanted to use an `except` statement\n"
1358 "with multiple exception types. If that is the case, you must\n"
1359 "surround them with parentheses.\n"
1360 )
1361 return {"cause": cause, "suggest": hint}
1362
1363
1364 @add_statement_analyzer
1365 def current_is_misspelled_python_keyword(statement):
1366 if not statement.bad_token.is_name():
1367 return {}
1368 # Before we make any attempt at modifying the original code,
1369 # we make sure that our statement checker can properly identify that
1370 # the original code is invalid. See #205
1371 if fixers.check_statement(statement.bad_line):
1372 return {}
1373 return misspelled_python_keyword(statement.tokens, statement.bad_token)
1374
1375
1376 @add_statement_analyzer
1377 def previous_is_misspelled_python_keyword(statement):
1378 if not statement.prev_token.is_name():
1379 return {}
1380 # Before we make any attempt at modifying the original code,
1381 # we make sure that our statement checker can properly identify that
1382 # the original code is invalid. See #205
1383 if fixers.check_statement(statement.bad_line):
1384 return {}
1385 return misspelled_python_keyword(statement.tokens, statement.prev_token)
1386
1387
1388 @add_statement_analyzer
1389 def space_in_variable_name(statement):
1390 # Looking for spaces in variable name assignments, like
1391 # my name = André
1392 bad_token = statement.bad_token
1393 prev_token = statement.prev_token
1394 if statement.highlighted_tokens and len(statement.highlighted_tokens) == 2:
1395 bad_token = statement.next_token
1396 prev_token = statement.bad_token
1397
1398 if not (
1399 bad_token.is_identifier()
1400 and prev_token.is_identifier()
1401 and prev_token is statement.first_token
1402 ):
1403 return {}
1404
1405 first_tokens = []
1406 for tok in statement.tokens:
1407 if tok == "=":
1408 # Note: there could be other errors
1409 cause = _(
1410 "You cannot have spaces in identifiers (variable names).\n"
1411 "Perhaps you meant `{name}`?\n"
1412 ).format(name="_".join(first_tokens))
1413 hint = _("Did you mean `{name}`?\n").format(name="_".join(first_tokens))
1414 return {"cause": cause, "suggest": hint}
1415
1416 if not tok.is_identifier():
1417 return {}
1418
1419 first_tokens.append(tok.string)
1420
1421 return {}
1422
1423
1424 @add_statement_analyzer
1425 def impossible_binary_fstring(statement):
1426 if (
1427 statement.bad_token.is_string()
1428 and statement.prev_token.string in ("bf", "fb")
1429 and statement.prev_token.immediately_before(statement.bad_token)
1430 ):
1431 hint = _("`bf` is an illegal string prefix.\n")
1432 cause = _(
1433 "I am guessing that you wanted a binary f-string;\n"
1434 "this is not allowed.\n"
1435 )
1436 return {"cause": cause, "suggest": hint}
1437
1438
1439 def _add_comma_or_operator(tokens, tok, comma_first=True):
1440 if comma_first:
1441 operators = ", ", " + ", " - ", " * ", " in "
1442 else:
1443 operators = " + ", " - ", " * ", ", ", " in "
1444 results = []
1445 for operator in operators:
1446 if operator == " in " and results:
1447 break
1448 new_statement = fixers.replace_token(tokens, tok, tok.string + operator)
1449 if fixers.check_statement(new_statement):
1450 results.append((operator.strip(), new_statement))
1451 return results
1452
1453
1454 def _comma_first_cause(bracket):
1455 if bracket == "(":
1456 return _(
1457 "It is possible that you "
1458 "forgot a comma between items in a tuple, \n"
1459 "or between function arguments, \n"
1460 "at the position indicated by ^.\n"
1461 )
1462
1463 if bracket == "[":
1464 return _(
1465 "It is possible that you "
1466 "forgot a comma between items in a list\n"
1467 "at the position indicated by ^.\n"
1468 )
1469
1470 return _(
1471 "It is possible that you "
1472 "forgot a comma between items in a set or dict\n"
1473 "at the position indicated by ^.\n"
1474 )
1475
1476
1477 @add_statement_analyzer
1478 def missing_comma_or_operator(statement):
1479 """Check to see if a comma or other operator
1480 is possibly missing between identifiers, or numbers, or both.
1481 """
1482 bad_token = statement.bad_token
1483 prev_token = statement.prev_token
1484 if statement.highlighted_tokens: # Python 3.10 may highlight two tokens
1485 bad_token = statement.next_token
1486 prev_token = statement.bad_token
1487 if not (
1488 bad_token.is_identifier() or bad_token.is_number() or bad_token.is_string()
1489 ) and not (
1490 prev_token.is_identifier() or prev_token.is_number() or prev_token.is_string()
1491 ):
1492 return {}
1493
1494 # Before we make any attempt at modifying the original code,
1495 # we make sure that our statement checker can properly identify that
1496 # the original code is invalid. See #205
1497 if fixers.check_statement(statement.bad_line):
1498 return {}
1499
1500 possible_cause = _(
1501 "Python indicates that the error is caused by "
1502 "`{second}` written immediately after `{first}`.\n"
1503 ).format(first=prev_token, second=bad_token)
1504
1505 if statement.begin_brackets:
1506 # likely inside a list, tuple, function def, dict, ...
1507 # in which case the most likely cause is a missing comma
1508 comma_first = True
1509 bracket = statement.begin_brackets[-1]
1510 comma_first_cause = _comma_first_cause(bracket)
1511 else:
1512 comma_first = False
1513 comma_first_cause = ""
1514
1515 new_statements = _add_comma_or_operator(
1516 statement.statement_tokens, prev_token, comma_first=comma_first
1517 )
1518 if not new_statements:
1519 return {}
1520
1521 if prev_token.start_row == bad_token.start_row:
1522 statement.location_markers = su.highlight_two_tokens(
1523 prev_token, bad_token, between="^"
1524 )
1525 else:
1526 statement.location_markers = su.highlight_two_tokens(
1527 prev_token, bad_token, first_marker="^", between="-->"
1528 )
1529
1530 # TODO: fix the cases with def/async/class
1531 if len(new_statements) == 1 or statement.first_token.string in [
1532 "def",
1533 "async",
1534 "class",
1535 ]:
1536 operator, line = new_statements[0]
1537 if "\n" in line:
1538 mark = su.highlight_added_token(prev_token, "^")
1539 line = su.add_mark_to_new_statement(
1540 statement, line, mark[prev_token.start_row]
1541 )
1542 # lines = line.split("\n")
1543 # lines = [" " + line_ for line_ in lines]
1544 # line = " \n".join(lines)
1545 else:
1546 # reducing multiple spaces on single line to single space for nicer display
1547 temp = line.split(" ")
1548 temp = [x for x in temp if x]
1549 line = " ".join(temp)
1550 mark = su.highlight_added_token(prev_token, "^")
1551 line = su.add_mark_to_new_statement(
1552 statement, line, mark[prev_token.start_row]
1553 )
1554 if "," in operator:
1555 hint = _("Did you forget a comma?\n")
1556 cause = possible_cause + comma_first_cause
1557 cause += _("Perhaps you meant{line}").format(line=utils.to_code_block(line))
1558 else:
1559 hint = _("Did you mean `{line}`?\n").format(line=line)
1560 cause = possible_cause
1561 else:
1562 operators = [operator for operator, line in new_statements]
1563 lines = [line for operator, line in new_statements]
1564 hint = _("Did you forget something between `{first}` and `{second}`?\n").format(
1565 first=prev_token, second=bad_token
1566 )
1567
1568 # The list of operators might include a comma; it is better to separate
1569 # items by semicolons
1570 if comma_first:
1571 operators = operators[1:]
1572 operators = utils.list_to_string(operators)
1573 else:
1574 operators = utils.list_to_string(operators, sep="; ")
1575
1576 cause = (
1577 possible_cause
1578 + comma_first_cause
1579 + _(
1580 "Perhaps you meant to insert an operator like `{operators}`\n"
1581 "between `{first}` and `{second}`.\n"
1582 "The following lines of code would not cause any `SyntaxError`:\n\n"
1583 ).format(first=prev_token, second=bad_token, operators=operators)
1584 )
1585 for line in lines:
1586 cause += f" {line}\n"
1587
1588 cause += _(
1589 "Note: these are just some of the possible choices and that\n"
1590 "some of them might raise other types of exceptions.\n"
1591 )
1592
1593 possible_cause = bracket_instead_of_paren(statement)
1594 if possible_cause:
1595 cause += "\n" + _("There is an additional possibility.\n")
1596 cause += possible_cause["cause"]
1597
1598 return {"cause": cause, "suggest": hint}
1599
1600
1601 @add_statement_analyzer
1602 def equal_instead_of_colon_in_dict(statement):
1603 if not (
1604 statement.begin_brackets
1605 and statement.bad_token == "="
1606 and statement.begin_brackets[-1] == "{"
1607 ):
1608 return {}
1609
1610 cause = _(
1611 "It is possible that "
1612 "you used an equal sign `=` instead of a colon `:`\n"
1613 "to assign values to keys in a dict\n"
1614 "before or at the position indicated by ^.\n"
1615 )
1616 return {"cause": cause}
1617
1618
1619 @add_statement_analyzer
1620 def boolean_instead_of_comma(statement):
1621 # Example: from math import sin and cos
1622 # Includes cases where boolean added after comma
1623 if statement.bad_token.string not in ["and", "or"]:
1624 return {}
1625 # Before we make any attempt at modifying the original code,
1626 # we make sure that our statement checker can properly identify that
1627 # the original code is invalid. See #205
1628 if fixers.check_statement(statement.bad_line):
1629 return {}
1630
1631 bad_token = statement.bad_token
1632
1633 possible_cause = _(
1634 "The Python keyword `{boolean}` can only be used for boolean expressions.\n"
1635 "Perhaps you meant to write\n\n"
1636 "`{new_statement}`\n"
1637 )
1638
1639 cause = None
1640 new_statement = fixers.replace_token(statement.statement_tokens, bad_token, ",")
1641 if fixers.check_statement(new_statement):
1642 cause = possible_cause.format(new_statement=new_statement, boolean=bad_token)
1643 else: # 'and' following a comma
1644 new_statement = fixers.replace_token(statement.statement_tokens, bad_token, "")
1645 if fixers.check_statement(new_statement):
1646 cause = possible_cause.format(
1647 new_statement=new_statement, boolean=bad_token
1648 )
1649
1650 return {"cause": cause} if cause else {}
1651
1652
1653 @add_statement_analyzer
1654 def from_import_as(statement):
1655 """from module import ... as ..., with 'as' flagged as the bad token"""
1656 if not (
1657 statement.bad_token == "as"
1658 and statement.first_token == "from"
1659 and statement.tokens[2] == "import"
1660 ):
1661 return {}
1662
1663 cause = _(
1664 "I am guessing that you are trying to import at least one object\n"
1665 "from module `{module}` and rename it using the Python keyword `as`;\n"
1666 "this keyword can only be used to rename one object at a time\n"
1667 "using a well defined syntax.\n"
1668 "I suggest that you split up any such import statement with each object\n"
1669 "renamed on a separate line as follows:\n\n"
1670 " from {module} import object_1 as name_1\n"
1671 " from {module} import object_2 as name_2 # if needed\n"
1672 ).format(module=statement.tokens[1])
1673 return {"cause": cause}
1674
1675
1676 @add_statement_analyzer
1677 def delete_names_or_items(statement):
1678 if statement.first_token != "del":
1679 return {}
1680
1681 cause = _(
1682 "You can only delete names of objects, or items in mutable containers\n"
1683 "such as `list`, `set`, or `dict`.\n"
1684 )
1685 return {"cause": cause}
1686
1687
1688 @add_statement_analyzer
1689 def duplicate_token(statement):
1690 if statement.bad_token != statement.prev_token:
1691 return {}
1692 bad_token = "`{bad_token}`".format(bad_token=statement.bad_token)
1693 cause = _(
1694 "I am guessing that you wrote {bad_token} twice in a row by mistake.\n"
1695 "If that is the case, you need to remove the second one.\n"
1696 ).format(bad_token=bad_token)
1697 hint = _("Did you write {bad_token} twice by mistake?\n").format(
1698 bad_token=bad_token
1699 )
1700 new_statement = fixers.replace_token(
1701 statement.statement_tokens, statement.bad_token, ""
1702 )
1703 # issue 205: check to see if original statement is found to be faulty.
1704 if fixers.check_statement(new_statement) and not fixers.check_statement(
1705 statement.bad_line
1706 ):
1707 return {"cause": cause, "suggest": hint}
1708 return {"cause": cause + more_errors(), "suggest": hint}
1709
1710
1711 @add_statement_analyzer
1712 def extra_token(statement):
1713 # Before we make any attempt at modifying the original code,
1714 # we make sure that our statement checker can properly identify that
1715 # the original code is invalid. See #205
1716 if fixers.check_statement(statement.bad_line):
1717 return {}
1718 new_statement = fixers.replace_token(
1719 statement.statement_tokens, statement.bad_token, ""
1720 )
1721
1722 if fixers.check_statement(new_statement):
1723 bad_token = "`{bad_token}`".format(bad_token=statement.bad_token)
1724 cause = _(
1725 "I am guessing that you wrote {bad_token} by mistake.\n"
1726 "Removing it and writing `{line}` seems to fix the error.\n"
1727 ).format(bad_token=bad_token, line=new_statement)
1728 hint = _("Did you write {bad_token} by mistake?\n").format(bad_token=bad_token)
1729 return {"cause": cause, "suggest": hint}
1730 return {}
1731
1732
1733 @add_statement_analyzer
1734 def missing_value_in_dict(statement):
1735 if not _possibly_inside_dict(statement):
1736 return {}
1737 if statement.bad_token.string not in [",", "}"]:
1738 return {}
1739 if statement.prev_token == ":":
1740 cause = _(
1741 "It looks like the error occurred as you were writing a Python dict.\n"
1742 "Perhaps you forgot to write a value after a colon.\n"
1743 )
1744 else:
1745 cause = _(
1746 "It looks like the error occurred as you were writing a Python dict.\n"
1747 "Perhaps wrote a dict key without writing the corresponding value.\n"
1748 )
1749 hint = _("Did you forget to write a dict value?\n")
1750 return {"cause": cause, "suggest": hint}
1751
1752
1753 @add_statement_analyzer
1754 def else_with_no_match(statement):
1755 if not (
1756 statement.bad_token == statement.first_token == "else"
1757 and statement.next_token == statement.last_token == ":"
1758 ):
1759 return {}
1760
1761 cause = _(
1762 "The `else` keyword does not begin a code block that matches\n"
1763 "a valid code block, possibly because `else` is not indented correctly.\n"
1764 )
1765 return {"cause": cause}
1766
1767
1768 @add_statement_analyzer
1769 def elif_with_no_matching_if(statement):
1770 if not (statement.bad_token == statement.first_token == "elif"):
1771 return {}
1772 if fixers.check_statement(statement.bad_line):
1773 cause = _(
1774 "The `elif` keyword does not begin a code block that matches\n"
1775 "an `if` block, possibly because `elif` is not indented correctly.\n"
1776 )
1777 return {"cause": cause}
1778 return {}
1779
1780
1781 @add_statement_analyzer
1782 def except_with_no_matching_try(statement):
1783 if not (statement.bad_token == statement.first_token == "except"):
1784 return {}
1785 if fixers.check_statement(statement.bad_line):
1786 cause = _(
1787 "The `except` keyword does not begin a code block that matches\n"
1788 "a `try` block, possibly because `except` is not indented correctly.\n"
1789 )
1790 return {"cause": cause}
1791 return {}
1792
1793
1794 @add_statement_analyzer
1795 def finally_with_no_matching_try(statement):
1796 if not (statement.bad_token == statement.first_token == "finally"):
1797 return {}
1798 if fixers.check_statement(statement.bad_line):
1799 cause = _(
1800 "The `finally` keyword does not begin a code block that matches\n"
1801 "a `try` block, possibly because `finally` is not indented correctly.\n"
1802 )
1803 return {"cause": cause}
1804 return {}
1805
1806
1807 @add_statement_analyzer
1808 def bracket_instead_of_paren(statement):
1809 if statement.statement_brackets:
1810 return {}
1811
1812 matching_pairs = []
1813 square_brackets = []
1814 for tok in statement.tokens:
1815 if tok == "[":
1816 square_brackets.append(tok)
1817 elif tok == "]":
1818 open_bracket = square_brackets.pop()
1819 matching_pairs.append((open_bracket, tok))
1820 if not matching_pairs:
1821 return {}
1822
1823 # Before we make any attempt at modifying the original code,
1824 # we make sure that our statement checker can properly identify that
1825 # the original code is invalid. See #205
1826 if fixers.check_statement(statement.bad_line):
1827 return {}
1828
1829 for first, second in matching_pairs:
1830 new_statement = fixers.replace_two_tokens(
1831 statement.statement_tokens,
1832 first,
1833 first_string="(",
1834 second_token=second,
1835 second_string=")",
1836 )
1837 if fixers.check_statement(new_statement):
1838 hint = _("You used square brackets, `[...]` instead of parentheses.\n")
1839 lines = new_statement.split("\n")
1840 new_lines = [f" {line}" for line in lines]
1841 new_statement = "\n".join(new_lines)
1842 cause = hint + _("Write the following instead:\n\n{new_statement}").format(
1843 new_statement=new_statement
1844 )
1845 return {"cause": cause, "suggest": hint}
1846 return {}
1847
1848
1849 # Last resort as it can catch odd cases where an unmatched open
1850 # bracket on one statement matches closing bracket on following
1851 # statement. Typically, the flagged token will be the first token
1852 # on a line, which Python detects as starting a new statement,
1853 # or the last token on the line.
1854 # The method I use to identify a statement can get matching
1855 # brackets from what is another Python statement.
1856 @add_statement_analyzer
1857 def unclosed_bracket(statement):
1858 if not statement.begin_brackets:
1859 return {}
1860
1861 bracket = statement.begin_brackets[-1]
1862 # not statement_brackets -> all brackets are closed
1863 # bad_token match open bracket: problem is not with unclosed bracket
1864 if not statement.statement_brackets and su.matching_brackets(
1865 bracket, statement.bad_token
1866 ):
1867 return {}
1868 # No unmatched brackets and Python did not identify a bad token as
1869 # either ending a statement or beginning a new statement
1870 if (
1871 not statement.statement_brackets
1872 and statement.bad_token.start_row == statement.prev_token.start_row
1873 and statement.bad_token.start_row == statement.next_token.start_row
1874 ):
1875 return {}
1876
1877 linenumber = bracket.start_row
1878 start_col = bracket.start_col
1879
1880 bracket_name = su.name_bracket(bracket)
1881 source = f"\n {linenumber}: {statement.source_lines[linenumber - 1]}"
1882 shift = len(str(linenumber)) + start_col + 6
1883 source += " " * shift + "^\n"
1884
1885 cause = (
1886 _("The opening {bracket} on line {linenumber} is not closed.\n").format(
1887 bracket=bracket_name, linenumber=linenumber
1888 )
1889 + source
1890 )
1891 if statement.statement_brackets: # no closing bracket
1892 return {"cause": cause}
1893
1894 # assume that the code is properly indented. If we go back to the same
1895 # level of indentation (or less) than the original statement, then
1896 # we definitely have an unclosed bracket
1897 first_column = statement.first_token.start_col
1898 for tok in statement.tokens[1:-1]:
1899 if tok.start_col <= first_column:
1900 cause += "\n" + _("If this is incorrect, please report this case.\n")
1901 return {"cause": cause}
1902
1903 # If the line flagged is not a valid statement, then we likely have other
1904 # problems.
1905 if not fixers.check_statement(statement.bad_line):
1906 return {}
1907
1908 tokens = token_utils.tokenize(statement.bad_line.strip())
1909 tokens = token_utils.remove_meaningless_tokens(tokens)
1910 if tokens[0].string in ["for", "if"] and tokens[-1] == ":":
1911 if bracket == "(":
1912 cause = _(
1913 "Perhaps you wrote a statement beginning a code block\n"
1914 "intended to be part of a generator expression.\n"
1915 "You cannot have separate code blocks inside generator expressions.\n"
1916 )
1917 elif bracket == "[":
1918 cause = _(
1919 "Perhaps you wrote a statement beginning a code block\n"
1920 "intended to be part of a list comprehension.\n"
1921 "You cannot have separate code blocks inside list comprehensions.\n"
1922 )
1923 else:
1924 cause = _(
1925 "Perhaps you wrote a statement beginning a code block\n"
1926 "intended to be part of a dict or set comprehension.\n"
1927 "You cannot have separate code blocks inside dict or set comprehensions.\n"
1928 )
1929
1930 cause += "\n" + _("If this explanation is incorrect, please report this case.\n")
1931 return {"cause": cause}