Debian Codegraph @

friendly_traceback/syntax_errors/message_analyzer.py

raw symbols SCIP
1 # type: ignore
2 """
3 Collection of functions that examine SyntaxError messages and
4 return relevant information to users.
5 """
6 import __future__
7
8 import ast
9 import re
10 import sys
11
12 from .. import debug_helper, token_utils, utils
13 from ..ft_gettext import current_lang, please_report
14 from . import error_in_def, fixers, statement_analyzer
15 from . import syntax_utils as su
16
17 MESSAGE_ANALYZERS = []
18 _ = current_lang.translate
19
20
21 def _assign_to_identifiers_only():
22 return _("You can only assign objects to identifiers (variable names).\n") # noqa
23
24
25 def _can_only_delete():
26 return _(
27 "You can only delete names of objects, or items in mutable containers\n"
28 "such as `list`, `set`, or `dict`.\n"
29 )
30
31
32 def _find_keyword(statement):
33 # used in assign_to_keyword
34 if statement.bad_token.is_keyword():
35 return statement.bad_token
36 elif statement.prev_token.is_keyword():
37 return statement.prev_token
38 else: # something like name.constant = ?
39 for tok in statement.tokens[statement.bad_token_index :]:
40 if tok.is_keyword():
41 return tok
42 debug_helper.log(f"Case not covered: {statement.bad_line}")
43 return None
44
45
46 def _what_kind_of_literal(literal):
47 """Evaluates an expression to see if we can determine its type."""
48 try:
49 a = ast.literal_eval(literal)
50 except Exception: # noqa
51 return ""
52
53 kinds = (
54 (int, _("of type `int`")),
55 (complex, _("of type `complex`")),
56 (float, _("of type `float`")),
57 (str, _("of type `str`")),
58 (dict, _("of type `dict`")),
59 (list, _("of type `list`")),
60 (set, _("of type `set`")),
61 (tuple, _("of type `tuple`")),
62 )
63 for kind, result in kinds:
64 if isinstance(a, kind):
65 return result
66
67 debug_helper.log(f"New kind of literal{str(a)}")
68 return "" # pragma: no cover
69
70
71 def _proper_decimal_or_octal_number(prev_str, bad_str):
72 # Used in invalid_token() and leading_zeros_in_decimal_integers()
73 if not (
74 set(prev_str).issubset("_0") and prev_str.startswith("0")
75 ): # pragma: no cover
76 debug_helper.log("_proper_decimal_or_octal_number should not have been called")
77 return {}
78
79 if prev_str == "0" and set(bad_str).issubset("01234567_"):
80 correct = f"0o{bad_str}"
81 hint = _("Did you mean `{num}`?\n").format(num=correct)
82 cause = _(
83 "Perhaps you meant to write the octal number `{num}`\n"
84 "and forgot the letter 'o', or perhaps you meant to write\n"
85 "a decimal integer and did not know that it could not start with zeros.\n"
86 ).format(num=correct)
87 return {"cause": cause, "suggest": hint}
88
89 if set(bad_str).issubset("0123456789_"):
90 correct = bad_str.lstrip("_")
91 hint = _("Did you mean `{num}`?\n").format(num=correct)
92 cause = _(
93 "Perhaps you meant to write the integer `{num}`\n"
94 "and did not know that it could not start with zeros.\n"
95 ).format(num=correct)
96 return {"cause": cause, "suggest": hint}
97
98 return {} # pragma: no cover
99
100
101 def add_python_message(func):
102 """A simple decorator that adds a function the list of functions
103 that process a message given by Python.
104 """
105 MESSAGE_ANALYZERS.append(func)
106
107 # The following is not normally needed; however, for debugging purpose
108 # we might wish to access the decorated function.
109 def wrapper():
110 return func()
111
112 return wrapper
113
114
115 def analyze_message(message: str = "", statement=None):
116 for case in MESSAGE_ANALYZERS:
117 cause = case(message, statement)
118 if cause:
119 return cause
120 return {}
121
122
123 @add_python_message
124 def assign_to_conditional_expression(message: str = "", statement=None):
125 if message not in (
126 "can't assign to conditional expression", # Python 3.6, 3.7
127 "cannot assign to conditional expression", # Python 3.8
128 ):
129 return {}
130
131 cause = _(
132 "On the left-hand side of an equal sign, you have a\n"
133 "conditional expression instead of the name of a variable.\n"
134 "A conditional expression has the following form:\n\n"
135 " variable = object if condition else other_object\n"
136 )
137
138 expression = su.get_expression_before_specified_token(
139 statement.bad_token, statement.tokens, "="
140 )
141 if expression is None:
142 return {
143 "cause": cause + _assign_to_identifiers_only(),
144 "suggest": _assign_to_identifiers_only(),
145 }
146 statement.location_markers = su.highlight_before_specified_token(
147 statement.bad_token, statement.tokens, "="
148 )
149 cause = _(
150 "On the left-hand side of an equal sign, you have a\n"
151 "conditional expression instead of the name of a variable.\n"
152 " {expression} = ...\n"
153 " {mark}\n"
154 ).format(
155 expression=expression,
156 mark=statement.location_markers[statement.first_token.start_row].strip(),
157 )
158
159 return {
160 "cause": cause + _assign_to_identifiers_only(),
161 "suggest": _assign_to_identifiers_only(),
162 }
163
164
165 @add_python_message
166 def assign_to_expression(message: str = "", _statement=None):
167 if message != "cannot assign to expression": # Python 3.10
168 return {}
169
170 cause = _(
171 "On the left-hand side of an equal sign, you have\n"
172 "an expression instead of the name of a variable.\n"
173 )
174 return {
175 "cause": cause + _assign_to_identifiers_only(),
176 "suggest": _assign_to_identifiers_only(),
177 }
178
179
180 @add_python_message
181 def assign_to_function_call(message: str = "", statement=None):
182 if (
183 message != "can't assign to function call" # Python 3.6, 3.7
184 and "cannot assign to function call" not in message
185 ):
186 return {}
187
188 hint = _assign_to_identifiers_only()
189
190 fn_call = su.get_expression_before_specified_token(
191 statement.bad_token, statement.tokens, "="
192 )
193 if fn_call is None:
194 fn_call = f"{statement.bad_token.string}(...)"
195 cause = _(
196 "You wrote the expression\n\n"
197 " {fn_call} = ...\n"
198 "where `{fn_call}`, on the left-hand side of the equal sign, either is\n"
199 "or includes a function call and is not simply the name of a variable.\n"
200 ).format(
201 fn_call=fn_call,
202 )
203 else:
204 statement.location_markers = su.highlight_before_specified_token(
205 statement.bad_token, statement.tokens, "="
206 )
207 cause = _(
208 "You wrote the expression\n\n"
209 " {fn_call} = ...\n"
210 " {mark}\n"
211 "where `{fn_call}`, on the left-hand side of the equal sign, either is\n"
212 "or includes a function call and is not simply the name of a variable.\n"
213 ).format(
214 fn_call=fn_call,
215 mark=statement.location_markers[statement.first_token.start_row].strip(),
216 )
217 return {"cause": cause + hint, "suggest": hint}
218
219
220 @add_python_message
221 def assign_to_generator_expression(message: str = "", statement=None):
222 if message not in (
223 "can't assign to generator expression", # Python 3.6, 3.7
224 "cannot assign to generator expression", # Python 3.8
225 ):
226 return {}
227
228 cause = _(
229 "On the left-hand side of an equal sign, you have a\n"
230 "generator expression instead of the name of a variable.\n"
231 )
232 expression = su.get_expression_before_specified_token(
233 statement.bad_token, statement.tokens, "="
234 )
235 if expression is not None:
236 statement.location_markers = su.highlight_before_specified_token(
237 statement.bad_token, statement.tokens, "="
238 )
239 hint = _assign_to_identifiers_only()
240 return {"cause": cause + hint, "suggest": hint}
241
242
243 @add_python_message
244 def assign_to_f_expression(message: str = "", statement=None):
245 if "cannot assign to f-string expression" in message:
246 cause = _(
247 "You wrote an expression that has the f-string `{fstring}`\n"
248 "on the left-hand side of the equal sign.\n"
249 "An f-string should only appear on the right-hand "
250 "side of an equal sign.\n"
251 ).format(fstring=statement.bad_token)
252 hint = _assign_to_identifiers_only()
253 return {"cause": cause + hint, "suggest": hint}
254 return {}
255
256
257 @add_python_message
258 def assign_to_keyword(message: str = "", statement=None):
259 if message not in (
260 "can't assign to keyword", # Python 3.6, 3.7
261 "assignment to keyword", # Python 3.6, 3.7
262 "cannot assign to keyword", # Python 3.8
263 "cannot assign to None", # Python 3.8
264 "cannot assign to True", # Python 3.8
265 "cannot assign to False", # Python 3.8
266 "cannot assign to __debug__", # Python 3.8
267 "can't assign to Ellipsis", # Python 3.6, 3.7
268 "cannot assign to Ellipsis", # Python 3.8
269 "cannot use named assignment with True", # Python 3.8
270 "cannot use named assignment with False", # Python 3.8
271 "cannot use named assignment with None", # Python 3.8
272 "cannot use named assignment with Ellipsis", # Python 3.8
273 "cannot use assignment expressions with True", # Python 3.8
274 "cannot use assignment expressions with False", # Python 3.8
275 "cannot use assignment expressions with None", # Python 3.8
276 "cannot use assignment expressions with Ellipsis", # Python 3.8
277 "cannot assign to Ellipsis here. Maybe you meant '==' instead of '='?",
278 "cannot assign to ellipsis here. Maybe you meant '==' instead of '='?",
279 ):
280 return {}
281
282 for word in ["None", "True", "False", "__debug__", "Ellipsis", "ellipsis"]:
283 if word in message:
284 break
285 else:
286 word = _find_keyword(statement)
287 if word is None:
288 return {}
289
290 hint = _("You cannot assign a value to `{keyword}`.\n").format(keyword=word)
291
292 if word in ["Ellipsis", "ellipsis"]:
293 hint = _("You cannot assign a value to the ellipsis symbol [`...`].\n")
294 cause = _(
295 "The ellipsis symbol `...` is a constant in Python;"
296 "you cannot assign it a different value.\n"
297 )
298 elif word in ["None", "True", "False", "__debug__"]:
299 cause = _(
300 "`{keyword}` is a constant in Python; you cannot assign it a different value.\n"
301 ).format(keyword=word)
302 else: # pragma: no cover
303 debug_helper.log(f"Case not covered: {statement.bad_line}")
304 cause = _(
305 "You were trying to assign a value to the Python keyword `{keyword}`.\n"
306 "This is not allowed.\n"
307 "\n"
308 ).format(keyword=word)
309
310 # Ensure that the bad token is highlighted; for example: a.__debug__ = 1
311 if statement.bad_token != word:
312 for tok in statement.tokens:
313 if tok == word:
314 statement.location_markers = su.highlight_single_token(tok)
315 break
316 return {"cause": cause, "suggest": hint}
317
318
319 def _assign_to_literal_in_for_loop(statement):
320 # see assign_to_literal() below
321 tokens = statement.tokens[: statement.bad_token_index]
322 for tok in tokens[::-1]:
323 if tok == "for":
324 cause = _(
325 "A for loop must have the form:\n\n"
326 " for ... in sequence:\n\n"
327 "where `...` must contain only identifiers (variable names)\n"
328 "and not literals like `{bad_token}`.\n"
329 ).format(bad_token=statement.bad_token)
330 return {"cause": cause, "suggest": _assign_to_identifiers_only()}
331 if tok == "in": # pragma: no cover
332 debug_helper.log("New case for assign_to_literal")
333 break
334 return {}
335
336
337 @add_python_message
338 def assign_to_literal(message: str = "", statement=None):
339 if message not in (
340 "can't assign to literal", # Python 3.6, 3.7
341 "cannot assign to literal", # Python 3.8
342 "cannot assign to set display", # Python 3.8
343 "cannot assign to dict display", # Python 3.8
344 "cannot assign to dict literal here. Maybe you meant '==' instead of '='?", # 3.10
345 "cannot assign to literal here. Maybe you meant '==' instead of '='?", # 3.10
346 "cannot assign to set display here. Maybe you meant '==' instead of '='?", # 3.10
347 ):
348 return {}
349
350 expression = su.get_expression_before_specified_token(
351 statement.bad_token, statement.tokens, "="
352 )
353 if expression is not None:
354 statement.location_markers = su.highlight_before_specified_token(
355 statement.bad_token, statement.tokens, "="
356 )
357
358 # This error can happen if we use a literal as an element of
359 # a for loop; we take care of this case first.
360 literal_in_for_loop = _assign_to_literal_in_for_loop(statement)
361 if literal_in_for_loop:
362 return literal_in_for_loop
363
364 line = statement.bad_line.rstrip()
365 parts = line.split("=")
366 if len(parts) == 2: # TODO: remove this limitation
367 literal = parts[0].strip()
368 name = parts[1].strip()
369 if sys.version_info < (3, 8) and (
370 literal.startswith("f'{") or literal.startswith('f"{')
371 ):
372 cause = _(
373 "You wrote an expression that has the f-string `{fstring}`\n"
374 "on the left-hand side of the equal sign.\n"
375 "An f-string should only appear on the right-hand "
376 "side of an equal sign.\n"
377 ).format(fstring=statement.bad_token)
378 return {"cause": cause}
379 else:
380 literal = expression if expression is not None else None
381 name = _("variable_name")
382
383 if len(parts) == 2 and name.isidentifier():
384 # fmt: off
385 suggest = _(
386 "Perhaps you meant to write:\n\n"
387 " {name} = {literal}\n"
388 "\n"
389 ).format(literal=literal, name=name)
390 # fmt: on
391 hint = _("Perhaps you meant to write `{name} = {literal}`").format(
392 literal=literal, name=name
393 )
394 else:
395 hint = _assign_to_identifiers_only()
396 suggest = "\n" + hint
397
398 # Impose the right type when we know it.
399 if message == "cannot assign to set display":
400 of_type = _what_kind_of_literal("{1}")
401 elif message == "cannot assign to dict display":
402 of_type = _what_kind_of_literal("{1:2}")
403 elif literal is None:
404 literal = "..."
405 of_type = ""
406 else:
407 of_type = _what_kind_of_literal(literal)
408
409 cause = (
410 _(
411 "You wrote an expression like\n\n"
412 " {literal} = {name}\n"
413 "where `{literal}`, on the left-hand side of the equal sign,\n"
414 "is or includes an actual object {of_type}\n"
415 "and is not simply the name of a variable.\n"
416 ).format(literal=literal, name=name, of_type=of_type)
417 + suggest
418 )
419 if statement.prev_token == "{":
420 cause += "\n" + _(
421 "It is possible that "
422 "you used an equal sign `=` instead of a colon `:`\n"
423 "to assign values to keys in a dict.\n"
424 )
425 return {"cause": cause, "suggest": hint}
426
427
428 @add_python_message
429 def assign_to_operator(message: str = "", statement=None):
430 bad_line = statement.bad_line.rstrip()
431 if message not in (
432 "can't assign to operator", # Python 3.6, 3.7
433 "cannot assign to operator", # Python 3.8
434 "cannot assign to expression here. Maybe you meant '==' instead of '='?", # Python 3.10
435 ):
436 return {}
437
438 cause = _(
439 "You wrote an expression that includes some mathematical operations\n"
440 "on the left-hand side of the equal sign which should be\n"
441 "only used to assign a value to a variable.\n"
442 )
443
444 def _could_be_identifier(line):
445 try:
446 if "=" in line and "-" in line:
447 lhs, *rhs = line.split("=")
448 if "-" in lhs:
449 lhs = lhs.replace("-", "_").strip()
450 if lhs.isidentifier():
451 return lhs
452 return ""
453 except Exception as e: # pragma: no cover
454 debug_helper.log(f"Problem in could_be_identifier:{str(e)}")
455 return ""
456
457 name = _could_be_identifier(bad_line)
458 if name:
459 hint = _("Did you mean `{name}`?\n").format(name=name)
460 cause += _(
461 "Perhaps you meant to write `{name}` instead of `{original}`\n"
462 ).format(name=name, original=name.replace("_", "-"))
463 return {"cause": cause, "suggest": hint}
464
465 hint = _("Perhaps you needed `==` instead of `=`.\n")
466 return {"cause": cause, "suggest": hint}
467
468
469 @add_python_message
470 def assign_to_yield_expression(message: str = "", _statement=None):
471 if message not in (
472 "can't assign to yield expression",
473 "cannot assign to yield expression",
474 "cannot assign to yield expression here. Maybe you meant '==' instead of '='?",
475 ):
476 return {}
477 cause = _(
478 "You wrote an expression that includes the `yield` keyword\n"
479 "on the left-hand side of the equal sign.\n"
480 "You cannot assign a value to such an expression.\n"
481 "Note that, like the keyword `return`,\n"
482 "`yield` can only be used inside a function.\n"
483 )
484 return {"cause": cause, "suggest": _assign_to_identifiers_only()}
485
486
487 @add_python_message
488 def assignment_cannot_rebind_inside_comprehension(message: str = "", _statement=None):
489 if (
490 "assignment expression cannot rebind comprehension iteration variable"
491 not in message
492 ):
493 return {}
494
495 var = message.split("'")[1]
496 cause = _(
497 "You are using the augmented assignment operator `:=` inside\n"
498 "a comprehension to assign a value to the iteration variable `{var}`.\n"
499 "This variable is meant to be used only inside the comprehension.\n"
500 "The augmented assignment operator is normally used to assign a value\n"
501 "to a variable so that the variable can be reused later.\n"
502 "This is not possible for variable `{var}`.\n"
503 ).format(var=var)
504 return {"cause": cause}
505
506
507 @add_python_message
508 def assignment_cannot_rebind_inside_comprehension_inner_loop(
509 message: str = "", _statement=None
510 ):
511 if (
512 "comprehension inner loop cannot rebind assignment expression target"
513 not in message
514 ):
515 return {}
516
517 var = message.split("'")[1]
518 cause = _(
519 "You are using the augmented assignment operator `:=` inside\n"
520 "a comprehension to assign a value to the iteration variable `{var}`.\n"
521 "This variable is meant to be used only inside the comprehension.\n"
522 "The augmented assignment operator is normally used to assign a value\n"
523 "to a variable so that the variable can be reused later.\n"
524 "This is not possible for variable `{var}`.\n"
525 ).format(var=var)
526 return {"cause": cause}
527
528
529 @add_python_message
530 def annotated_name_cannot_be_global(message: str = "", statement=None):
531 pattern1 = re.compile(r"annotated name '(.*)' can't be global")
532 match = re.search(pattern1, message)
533 if not match:
534 return {}
535 cause = _(
536 "The object named `{name}` is defined with type annotation\n"
537 "as a local variable. It cannot be declared to be a global variable.\n"
538 ).format(name=match[1])
539 # Ensure that only the variable gets highlighted for consistency
540 # across all Python versions.
541 statement.location_markers = su.highlight_single_token(statement.bad_token)
542 return {"cause": cause}
543
544
545 @add_python_message
546 def augmented_assignment_with_literal(message: str = "", statement=None):
547 if message != "cannot use assignment expressions with literal":
548 return {}
549
550 cause = _(
551 "You cannot use the augmented assignment operator `:=`,\n"
552 "sometimes called the walrus operator, with literals like `{bad_token}`.\n"
553 "You can only assign objects to identifiers (variable names).\n"
554 ).format(bad_token=statement.bad_token)
555 return {"cause": cause, "suggest": _assign_to_identifiers_only()}
556
557
558 @add_python_message
559 def both_nonlocal_and_global(message: str = "", statement=None):
560 if "is nonlocal and global" in message:
561 cause = _(
562 "You declared `{name}` as being both a global and nonlocal variable.\n"
563 "A variable can be global, or nonlocal, but not both at the same time.\n"
564 ).format(name=statement.next_token)
565 return {"cause": cause}
566 return {}
567
568
569 @add_python_message
570 def bracket_was_expected(message: str = "", statement=None):
571 pattern = re.compile("'(.*)' was never closed") # new in Python 3.10
572 match = re.search(pattern, message)
573 if not match:
574 return {}
575
576 cause = _("Python tells us that the {bracket} was never closed.\n").format(
577 bracket=su.name_bracket(match[1])
578 )
579 hint = _("The {bracket} was never closed.\n").format(
580 bracket=su.name_bracket(match[1])
581 )
582 rephrased_cause = statement_analyzer.unclosed_bracket(statement)
583 if rephrased_cause:
584 cause = rephrased_cause["cause"]
585 return {"cause": cause, "suggest": hint}
586
587
588 @add_python_message
589 def break_outside_loop(message: str = "", _statement=None):
590 if "'break' outside loop" in message:
591 cause = _(
592 "The Python keyword `break` can only be used "
593 "inside a `for` loop or inside a `while` loop.\n"
594 )
595 return {"cause": cause}
596 return {}
597
598
599 @add_python_message
600 def cannot_assign_to_attribute(message: str = "", statement=None):
601 if "cannot assign to attribute here" not in message: # new in Python 3.10
602 return {}
603 hint = _("Perhaps you needed `==` instead of `=`.\n")
604 cause = _(
605 "You likely used an assignment operator `=` instead of an equality operator `==`.\n"
606 )
607
608 for tok in statement.tokens[statement.bad_token_index :]:
609 if tok == "=":
610 new_statement = fixers.replace_token(statement.statement_tokens, tok, "==")
611 if fixers.check_statement(new_statement):
612 cause += _(
613 "The following statement would not contain a syntax error:\n\n"
614 " {new_statement}\n"
615 ).format(new_statement=new_statement)
616
617 return {"cause": cause, "suggest": hint}
618
619
620 @add_python_message
621 def cannot_delete_constant(message: str = "", statement=None):
622 if message not in (
623 "can't delete keyword", # Python 3.6, 3.7
624 "cannot delete None",
625 "cannot delete True",
626 "cannot delete False",
627 "cannot delete __debug__", # Python 3.10+
628 ):
629 return {}
630
631 cause = (
632 _("You cannot delete the constant `{constant}`.\n").format(
633 constant=statement.bad_token
634 )
635 + _can_only_delete()
636 )
637 return {"cause": cause}
638
639
640 @add_python_message
641 def cannot_delete_expression(message: str = "", statement=None):
642 if message not in (
643 "can't delete operator", # Python 3.6
644 "cannot delete operator", # Python 3.8
645 "cannot delete expression", # Python 3.10
646 ):
647 return {}
648 if statement.first_token != "del":
649 debug_helper.log(
650 f"Expected first token to be 'del'; got {statement.first_token}"
651 )
652 cause = _("You cannot delete a Python expression.\n")
653 else:
654 expression = statement.bad_line[3:].strip() # remove del
655 cause = _("You cannot delete the expression `{expression}`.\n").format(
656 expression=expression
657 )
658 hint = _can_only_delete()
659 return {"cause": cause + _can_only_delete(), "suggest": hint}
660
661
662 @add_python_message
663 def cannot_delete_function_call(message: str = "", statement=None):
664 if message not in (
665 "can't delete function call", # Python 3.6, 3.7
666 "cannot delete function call", # Python 3.8
667 ):
668 return {}
669
670 line = statement.bad_line.rstrip()
671 correct = "del {name}".format(name=statement.bad_token)
672 cause = _(
673 "You attempted to delete a function call\n\n"
674 " {line}\n"
675 "instead of deleting the function's name\n\n"
676 " {correct}\n"
677 ).format(line=line, correct=correct)
678 return {"cause": cause}
679
680
681 @add_python_message
682 def cannot_delete_literal(message: str = "", statement=None):
683 if message not in (
684 "can't delete literal", # Python 3.6, 3.7
685 "cannot delete literal",
686 ):
687 return {}
688
689 cause = (
690 _("You cannot delete the literal `{literal}`.\n").format(
691 literal=statement.bad_token
692 )
693 + _can_only_delete()
694 )
695 return {"cause": cause}
696
697
698 @add_python_message
699 def cannot_delete_named_expression(message: str = "", statement=None):
700 if message not in ("cannot delete named expression",): # Python 3.8 +
701 return {}
702 if statement.first_token != "del":
703 debug_helper.log(
704 f"Expected first token to be 'del'; got {statement.first_token}"
705 )
706 cause = _("You cannot delete a Python expression.\n")
707 else:
708 expression = statement.bad_line[3:].strip() # remove del
709 cause = _("You cannot delete the named expression `{expression}`.\n").format(
710 expression=expression
711 )
712 hint = _can_only_delete()
713 return {"cause": cause + _can_only_delete(), "suggest": hint}
714
715
716 @add_python_message
717 def cannot_use_starred_expression(message: str = "", statement=None):
718 if message not in [
719 "can't use starred expression here",
720 "cannot use starred expression here",
721 "cannot delete starred",
722 ]:
723 return {}
724
725 cause = _(
726 "The star operator `*` is interpreted to mean that\n"
727 "iterable unpacking is to be used to assign a name\n"
728 "to each item of an iterable, which does not make sense here.\n"
729 )
730 if statement.first_token == "del":
731 cause += _can_only_delete()
732 elif (
733 len(statement.tokens) > statement.bad_token_index + 2
734 and statement.prev_token == "("
735 and statement.next_token.is_identifier()
736 and statement.tokens[statement.bad_token_index + 2] == ")"
737 and sys.version_info >= (3, 9)
738 ):
739 cause += "\n" + _(
740 "It looks like you surrounded a starred name by parentheses.\n"
741 "This was not considered a SyntaxError before Python version 3.9.\n"
742 )
743
744 return {"cause": cause}
745
746
747 @add_python_message
748 def colon_expected(message: str = "", statement=None):
749 if message != "expected ':'": # new in Python 3.10
750 return {}
751
752 # Try to be consistent with older versions
753 cause = statement_analyzer.missing_colon(statement)
754 if cause:
755 return cause
756
757 # That did not work, so we try something else
758 hint = _("Did you forget a colon?\n")
759 cause = _("Python expected a colon at the position indicated.\n")
760
761 new_statement = fixers.replace_token(
762 statement.statement_tokens, statement.bad_token, ":"
763 )
764 if fixers.check_statement(new_statement):
765 cause += _("You wrote `{bad}` instead of a colon.\n").format(
766 bad=statement.bad_token
767 )
768 return {"cause": cause, "suggest": hint}
769
770 new_statement = fixers.replace_token(
771 statement.statement_tokens,
772 statement.bad_token,
773 f"{statement.bad_token.string}:",
774 )
775
776 if fixers.check_statement(new_statement): # pragma: no cover
777 debug_helper.log("New case for colon_expected.")
778 return {"cause": cause, "suggest": hint}
779
780 return {}
781
782
783 @add_python_message
784 def colon_missing_after_dict_key(message: str = "", _statement=None):
785 if message != "':' expected after dictionary key":
786 return {}
787 cause = _(
788 "It looks like the error occurred as you were writing a Python dict.\n"
789 "Perhaps you wrote a dict key without writing the corresponding value.\n"
790 )
791 hint = _("Did you forget to write a dict value?\n")
792 return {"cause": cause, "suggest": hint}
793
794
795 @add_python_message
796 def continue_outside_loop(message: str = "", _statement=None):
797 if "'continue' not properly in loop" in message:
798 cause = _(
799 "The Python keyword `continue` can only be used "
800 "inside a `for` loop or inside a `while` loop.\n"
801 )
802 return {"cause": cause}
803 return {}
804
805
806 @add_python_message
807 def duplicate_argument_in_function_definition(message: str = "", statement=None):
808 if "duplicate argument" in message and "function definition" in message:
809 name = message.split("'")[1]
810 cause = _(
811 "You have defined a function repeating the argument\n\n"
812 " {name}\n"
813 "Each argument should appear only once in a function definition.\n"
814 ).format(name=name)
815 locate_duplicate_arguments(statement, name)
816 return {"cause": cause}
817
818 return {}
819
820
821 def locate_duplicate_arguments(statement, name):
822 # Make sure that we do not include the function name
823 begin_args = False
824 args = []
825 for token in statement.tokens:
826 if token == "(":
827 begin_args = True
828 if not begin_args:
829 continue
830 if token == name:
831 args.append(token)
832
833 markers = {}
834 for token in args:
835 if token.start_row not in markers:
836 markers[token.start_row] = " " * token.start_col + "^" * len(token.string)
837 else:
838 markers[token.start_row] += " " * (
839 token.start_col - prev_token.end_col # noqa
840 ) + "^" * len(token.string)
841 prev_token = token # noqa
842 statement.location_markers = markers
843
844
845 @add_python_message
846 def else_after_if(message: str = "", _statement=None):
847 if message != "expected 'else' after 'if' expression":
848 return {}
849
850 hint = _("Did you forget to add `else`?\n")
851 cause = _("An `else some_value` clause was expected after the `if` expression.\n")
852 return {"cause": cause, "suggest": hint}
853
854
855 @add_python_message
856 def eof_unclosed_triple_quoted(message: str = "", _statement=None):
857 if not (
858 message == "EOF while scanning triple-quoted string literal"
859 or "unterminated triple-quoted string literal" in message
860 ):
861 return {}
862
863 cause = _(
864 "You started writing a triple-quoted string but never wrote\n"
865 "the triple quotes needed to end the string.\n"
866 )
867
868 return {"cause": cause}
869
870
871 @add_python_message
872 def eol_while_scanning_string_literal(message: str = "", statement=None):
873 if not (
874 "EOL while scanning string literal" in message
875 or "unterminated string literal" in message # Python 3.10+
876 ):
877 return {}
878
879 # Default explanation
880 hint = _("Did you forget a closing quote?\n")
881 cause = _(
882 "You started writing a string with a single or double quote\n"
883 "but never ended the string with another quote on that line.\n"
884 )
885
886 for token in statement.tokens:
887 if token.is_error():
888 statement.location_markers = su.highlight_single_token(token)
889 break
890
891 # skipcq: PYL-R1714
892 # second if case for Python 3.10
893 if statement.prev_token == "\\" or statement.bad_line[-2] == "\\":
894 cause += _(
895 "Perhaps you meant to write the backslash character, `\\`\n"
896 "as the last character in the string and forgot that you\n"
897 "needed to escape it by writing two `\\` in a row.\n"
898 )
899 hint = _("Did you forget to escape a backslash character?\n")
900
901 # Perhaps we have an unescaped inner quote:
902 # ... 'I don't care.'
903 # This gave "SyntaxError: invalid syntax" prior to Python 3.10.
904
905 previous_string = None
906 for tok in statement.tokens:
907 if tok == statement.bad_token:
908 break
909 if tok.is_string():
910 previous_string = tok
911
912 if (
913 previous_string is not None
914 and previous_string.string[-1] == statement.bad_token
915 ):
916 new_tokens = []
917 for tok in statement.tokens:
918 if tok == previous_string:
919 s = tok.string[:-1] + tok.string[-1].replace("'", "\\'").replace(
920 '"', '\\"'
921 )
922 tok_copy = previous_string.copy()
923 tok_copy.string = s
924 new_tokens.append(tok_copy)
925 else:
926 new_tokens.append(tok)
927 new_line = token_utils.untokenize(new_tokens)
928 if fixers.check_statement(new_line):
929 quote_position = previous_string.end_col
930 indent = len(statement.bad_line) - len(statement.bad_line.lstrip())
931 quote_position -= indent
932 mark = " " * (quote_position - 1) + "^^"
933
934 hint = _("Perhaps you forgot to escape a quote character.\n")
935 cause = _(
936 "I suspect that you were trying to use a quote character inside a string\n"
937 "that was enclosed in quotes of the same kind.\n"
938 "Perhaps you should have escaped the inner quote character:\n\n"
939 " {new_line}\n"
940 " {mark}\n"
941 ).format(new_line=new_line, mark=mark)
942
943 return {"cause": cause, "suggest": hint}
944
945
946 @add_python_message
947 def expected_except_or_finally(message: str = "", statement=None):
948 if message != "expected 'except' or 'finally' block": # new in 3.10
949 return {}
950 cause = _(
951 "You wrote a `try` block which did not include an `except` nor a `finally` block.\n"
952 )
953
954 if fixers.check_statement(statement.bad_line):
955 # our checker does not see a problem, so it cannot be used reliably
956 # to find a fix
957 return {"cause": cause}
958
959 hint = ""
960 similar = utils.get_similar_words(statement.tokens[0].string, ["except", "finally"])
961 tokens = statement.tokens
962 if similar:
963 new_statement = fixers.replace_token(tokens, tokens[0], similar[0])
964 if fixers.check_statement(new_statement):
965 cause += _("Perhaps you meant to write\n\n {new_statement}").format(
966 new_statement=new_statement
967 )
968 hint = _("Did you mean `{new_statement}`?").format(new_statement=new_statement)
969 else:
970 new_statement = fixers.replace_token(tokens, tokens[0], "except")
971 with_except = fixers.check_statement(new_statement)
972 new_statement2 = fixers.replace_token(tokens, tokens[0], "finally")
973 with_finally = fixers.check_statement(new_statement2)
974 if with_except and with_finally:
975 cause += _(
976 "Perhaps you meant to write either\n\n"
977 " {new_statement}"
978 "\n\nor\n\n"
979 " {new_statement2}"
980 ).format(new_statement=new_statement, new_statement2=new_statement2)
981 elif with_except:
982 cause += _("Perhaps you meant to write\n\n {new_statement}").format(
983 new_statement=new_statement
984 )
985 hint = _("Did you mean `{new_statement}`?").format(
986 new_statement=new_statement
987 )
988
989 return {"cause": cause, "suggest": hint} if hint else {"cause": cause}
990
991
992 @add_python_message
993 def expected_paren(message: str = "", statement=None):
994 if message != "expected '('":
995 return {}
996
997 if statement.first_token == "def" or (
998 statement.first_token == "async" and statement.tokens[1] == "def"
999 ):
1000 cause = error_in_def.analyze_def_statement(statement)
1001 if cause:
1002 return cause
1003 return {}
1004
1005
1006 @add_python_message
1007 def expression_cannot_contain_assignment(message: str = "", statement=None):
1008 if (
1009 "expression cannot contain assignment, perhaps you meant" not in message
1010 and "keyword can't be an expression" not in message
1011 ):
1012 return {}
1013 if statement.bad_token.is_keyword() or statement.next_token.is_keyword():
1014 if statement.bad_token.is_keyword():
1015 keyword = statement.bad_token
1016 else:
1017 keyword = statement.next_token
1018 hint = _("You cannot assign a value to `{keyword}`.\n").format(keyword=keyword)
1019 cause = (
1020 _(
1021 "You likely called a function using the Python keyword"
1022 " `{keyword}` as an argument:\n\n"
1023 " a_function({keyword}=something) \n\n"
1024 "which Python interpreted as trying to assign a value to a Python keyword.\n"
1025 "\n"
1026 ).format(keyword=keyword)
1027 + hint
1028 )
1029 return {"cause": cause, "suggest": hint}
1030
1031 cause = _(
1032 "You likely called a function with a named argument:\n\n"
1033 " a_function(invalid=something) \n\n"
1034 "where `invalid` is not a valid variable name in Python\n"
1035 "either because it starts with a number, or is a string,\n"
1036 "or contains a period, etc.\n"
1037 )
1038 return {"cause": cause}
1039
1040
1041 @add_python_message
1042 def expression_missing_after_dict_key_and_colon(message: str = "", _statement=None):
1043 if message != "expression expected after dictionary key and ':'":
1044 return {}
1045 cause = _(
1046 "It looks like the error occurred as you were writing a Python dict.\n"
1047 "Perhaps you forgot to write a value after a colon.\n"
1048 )
1049 hint = _("Did you forget to write a dict value?\n")
1050 return {"cause": cause, "suggest": hint}
1051
1052
1053 @add_python_message
1054 def f_string_backslash(message: str = "", _statement=None):
1055 if message != "f-string expression part cannot include a backslash":
1056 return {}
1057
1058 cause = _(
1059 "You have written an f-string whose content `{...}`\n"
1060 "includes a backslash; this is not allowed.\n"
1061 "Perhaps you can replace the part that contains a backslash by\n"
1062 "some variable. For example, suppose that you have an f-string like:\n\n"
1063 " f\"{... 'hello\\n' ...}\"\n\n"
1064 "you could write this as\n\n"
1065 " hello = 'hello\\n'\n"
1066 ' f"{... hello ...}"\n'
1067 )
1068 return {"cause": cause}
1069
1070
1071 @add_python_message
1072 def f_string_curly_not_allowed(message: str = "", _statement=None):
1073 if message != "f-string: single '}' is not allowed":
1074 return {}
1075 cause = _(
1076 "You have written an f-string which has an unmatched `}`.\n"
1077 "If you want to print a single `}`, you need to write `}}` in the f-string;\n"
1078 "otherwise, you need to add an opening `{`.\n"
1079 )
1080 return {"cause": cause}
1081
1082
1083 @add_python_message
1084 def f_string_expecting_curly(message: str = "", _statement=None):
1085 if message != "f-string: expecting '}'":
1086 return {}
1087 cause = _(
1088 "You have written an f-string which has an unmatched `{`.\n"
1089 "If you want to print a single `{`, you need to write `{{` in the f-string;\n"
1090 "otherwise, you need to add a closing `}`.\n"
1091 )
1092 return {"cause": cause}
1093
1094
1095 @add_python_message
1096 def forgot_paren_around_comprehension(message: str = "", _statement=None):
1097 # Python 3.10+
1098 if message != "did you forget parentheses around the comprehension target?":
1099 return {}
1100
1101 # message same as from statement_analyzer.comprehension_condition_or_tuple
1102
1103 cause_tuple = _(
1104 "I am guessing that you were writing a comprehension or a generator expression\n"
1105 "and forgot to include parentheses around tuples.\n"
1106 "As an example, instead of writing\n\n"
1107 " [i, i**2 for i in range(10)]\n\n"
1108 "you would need to write\n\n"
1109 " [(i, i**2) for i in range(10)]\n\n"
1110 )
1111 hint = _("Did you forget parentheses?\n")
1112 return {"cause": cause_tuple, "suggest": hint}
1113
1114
1115 @add_python_message
1116 def from__future__at_begin(message: str = "", _statement=None):
1117 if message != "from __future__ imports must occur at the beginning of the file":
1118 return {}
1119
1120 cause = _(
1121 "A `from __future__ import` statement changes the way Python\n"
1122 "interprets the code in a file.\n"
1123 "It must appear at the beginning of the file."
1124 )
1125 return {"cause": cause}
1126
1127
1128 @add_python_message
1129 def from__future__not_defined(message: str = "", _statement=None):
1130 pattern = re.compile(r"future feature (.*) is not defined")
1131 match = re.search(pattern, message)
1132 if match is None:
1133 return {}
1134
1135 names = __future__.all_feature_names
1136 available = _("The available features are `{names}`.\n").format(
1137 names=utils.list_to_string(names).replace(",", ",\n")
1138 )
1139 feature = match[1]
1140 if feature == "*":
1141 cause = _(
1142 "When using a `from __future__ import` statement,\n"
1143 "you must import specific named features.\n"
1144 )
1145 cause += "\n" + available
1146 return {"cause": cause}
1147
1148 names = __future__.all_feature_names
1149 similar = utils.get_similar_words(feature, names)
1150 if similar:
1151 hint = _("Did you mean `{name}`?\n").format(name=similar[0])
1152 cause = _(
1153 "Instead of `{feature}`, perhaps you meant to import `{name}`.\n"
1154 ).format(feature=feature, name=similar[0])
1155 return {"cause": cause, "suggest": hint}
1156
1157 cause = _("`{feature}` is not a valid feature of module `__future__`.\n").format(
1158 feature=feature
1159 )
1160 cause += "\n" + available
1161 return {"cause": cause}
1162
1163
1164 @add_python_message
1165 def function_parameters_cannot_be_paren(message: str = "", statement=None):
1166 if message != "Function parameters cannot be parenthesized":
1167 return {}
1168
1169 if statement.first_token == "def" or (
1170 statement.first_token == "async" and statement.tokens[1] == "def"
1171 ):
1172 cause = error_in_def.analyze_def_statement(statement)
1173 if cause:
1174 return cause
1175 return {}
1176
1177
1178 @add_python_message
1179 def generator_expression_must_be_parenthesized(message: str = "", _statement=None):
1180 if "Generator expression must be parenthesized" not in message:
1181 return {}
1182 cause = _(
1183 "You are using a generator expression, something of the form\n\n"
1184 " x for x in thing\n\n"
1185 "You must add parentheses enclosing that expression.\n"
1186 )
1187 return {"cause": cause}
1188
1189
1190 @add_python_message
1191 def import_braces(message: str = "", _statement=None):
1192 if message != "not a chance":
1193 return {}
1194
1195 cause = _(
1196 "I suspect you wrote `from __future__ import braces` following\n"
1197 "someone else's suggestion. This will never work.\n\n"
1198 "Unlike other programming languages, Python's code block are defined by\n"
1199 "their indentation level, and not by using some curly braces, like `{...}`.\n"
1200 )
1201 return {"cause": cause}
1202
1203
1204 @add_python_message
1205 def invalid_character_in_identifier(message: str = "", statement=None):
1206 if "invalid character" not in message:
1207 return {}
1208
1209 bad_character = statement.bad_token.string
1210 copy_paste = _("Did you use copy-paste?\n")
1211 python_says = _(
1212 "Python indicates that you used the unicode character"
1213 " `{bad_character}`\n"
1214 "which is not allowed.\n"
1215 ).format(bad_character=bad_character)
1216
1217 potential_cause = su.identify_bad_quote_char(bad_character, statement.bad_line)
1218 if potential_cause:
1219 potential_cause["cause"] = copy_paste + python_says + potential_cause["cause"]
1220 return potential_cause
1221
1222 potential_cause = su.identify_unicode_fraction(bad_character)
1223 if potential_cause:
1224 potential_cause["cause"] = copy_paste + python_says + potential_cause["cause"]
1225 return potential_cause
1226
1227 return {"cause": python_says}
1228
1229
1230 @add_python_message
1231 def invalid_decimal_literal(message: str = "", statement=None):
1232 if message != "invalid decimal literal": # new in Python 3.10
1233 return {}
1234 if not statement.highlighted_tokens or len(statement.highlighted_tokens) == 1:
1235 statement.highlighted_tokens = [statement.bad_token, statement.next_token]
1236
1237 cause_prefix = _("Python tells us that you have written an invalid number.")
1238 however = _("However, I think that the problem might be the following.")
1239
1240 if statement.first_token == "def" or (
1241 statement.first_token == "async" and statement.tokens[1] == "def"
1242 ):
1243 cause = error_in_def.analyze_def_statement(statement)
1244 if cause:
1245 cause["cause"] = cause_prefix + "\n" + however + "\n\n" + cause["cause"]
1246 return cause
1247
1248 cause = statement_analyzer.invalid_name(statement)
1249 if cause:
1250 cause["cause"] = cause_prefix + "\n" + however + "\n\n" + cause["cause"]
1251 return cause
1252
1253 if statement.next_token is not None and statement.bad_token.is_number():
1254 bad_character = statement.next_token.string
1255 potential_cause = su.identify_bad_math_symbol(bad_character, statement.bad_line)
1256 if potential_cause:
1257 potential_cause["cause"] = (
1258 cause_prefix + "\n" + however + "\n\n" + potential_cause["cause"]
1259 )
1260 return potential_cause
1261
1262 potential_cause = su.identify_unicode_fraction(bad_character)
1263 if potential_cause:
1264 potential_cause["cause"] = (
1265 cause_prefix + "\n" + however + "\n\n" + potential_cause["cause"]
1266 )
1267 return potential_cause
1268
1269 return {
1270 "cause": cause_prefix
1271 + "\n"
1272 + _("I have no suggestion to offer to fix this problem.\n")
1273 + please_report()
1274 }
1275
1276
1277 @add_python_message
1278 def invalid_double_star_operator(message: str = "", _statement=None):
1279 # Used to be "invalid syntax" prior to Python version 3.10
1280 if message == "f-string: cannot use double starred expression here":
1281 cause = _(
1282 "The double star operator `**` is likely interpreted to mean that\n"
1283 "dict unpacking is to be used which is not allowed or does not make sense here.\n"
1284 )
1285 return {"cause": cause}
1286
1287 return {}
1288
1289
1290 @add_python_message
1291 def invalid_hexadecimal_literal(message: str = "", statement=None):
1292 if message != "invalid hexadecimal literal": # new in Python 3.10
1293 return {}
1294 if not statement.highlighted_tokens:
1295 statement.highlighted_tokens = [statement.bad_token, statement.next_token]
1296
1297 if statement.first_token == "def" or (
1298 statement.first_token == "async" and statement.tokens[1] == "def"
1299 ):
1300 cause = error_in_def.analyze_def_statement(statement)
1301 if cause:
1302 return cause
1303
1304 return statement_analyzer.invalid_hexadecimal(statement)
1305
1306
1307 @add_python_message
1308 def invalid_imaginary_literal(message: str = "", statement=None):
1309 if message != "invalid imaginary literal": # new in Python 3.10
1310 return {}
1311 if not statement.highlighted_tokens or len(statement.highlighted_tokens) == 1:
1312 statement.highlighted_tokens = [statement.bad_token, statement.next_token]
1313
1314 if statement.first_token == "def" or (
1315 statement.first_token == "async" and statement.tokens[1] == "def"
1316 ):
1317 cause = error_in_def.analyze_def_statement(statement)
1318 if cause:
1319 return cause
1320
1321 return statement_analyzer.invalid_name(statement)
1322
1323
1324 @add_python_message
1325 def invalid_octal(message: str = "", statement=None):
1326 # Before Python 3.8, we'd only get "invalid syntax"
1327 if "in octal literal" not in message:
1328 return {}
1329
1330 return statement_analyzer.invalid_octal(statement)
1331
1332
1333 @add_python_message
1334 def iterable_unpacking_cannot_be_used_in_comprehension(
1335 message: str = "", statement=None
1336 ):
1337 if message != "iterable unpacking cannot be used in comprehension":
1338 return {}
1339 cause = _(
1340 "You cannot use the `*` operator to unpack the iteration variable\n"
1341 "in a comprehension.\n"
1342 )
1343 if statement.bad_token == "*":
1344 bad_token = statement.bad_token
1345 elif statement.next_token == "*":
1346 bad_token = statement.next_token
1347 else:
1348 return {"cause": cause}
1349 new_statement = fixers.replace_token(statement.statement_tokens, bad_token, "")
1350 if fixers.check_statement(new_statement):
1351 cause += "\n" + _(
1352 "The following statement has no syntax error:\n\n {statement}\n"
1353 ).format(statement=new_statement)
1354 return {"cause": cause}
1355
1356
1357 @add_python_message
1358 def invalid_token(message: str = "", statement=None):
1359 # Seen this for Python 3.6, 3.7 for would-be decimal number starting with zero.
1360 if message != "invalid token":
1361 return {}
1362
1363 prev_str = statement.prev_token.string
1364 bad_str = statement.bad_token.string
1365 return _proper_decimal_or_octal_number(prev_str, bad_str)
1366
1367
1368 @add_python_message
1369 def keyword_argument_repeated(message: str = "", statement=None):
1370 if "keyword argument repeated" not in message:
1371 return {}
1372 cause = _(
1373 "You have called a function repeating the same keyword argument (`{arg}`).\n"
1374 "Each keyword argument should appear only once in a function call.\n"
1375 ).format(arg=statement.bad_token)
1376 return {"cause": cause}
1377
1378
1379 @add_python_message
1380 def lambda_expression_parameters_cannot_be_paren(message: str = "", statement=None):
1381 if message != "Lambda expression parameters cannot be parenthesized":
1382 return {}
1383
1384 cause = statement_analyzer.lambda_with_paren(statement)
1385 return cause or {}
1386
1387
1388 @add_python_message
1389 def leading_zeros_in_decimal_integers(message: str = "", statement=None):
1390 # Same as previous case but for Python 3.8+
1391 if not (
1392 message.startswith(
1393 "leading zeros in decimal integer literals are not permitted"
1394 )
1395 ):
1396 return {}
1397
1398 # Suppose problem is string 01
1399 # Prior to Python 3.12, statement.bad_token.string would have been 0.
1400 # For Python 3.12, this would be 01.
1401
1402 if statement.bad_token.string[0] == "0":
1403 no_leading_zeros = statement.bad_token.string.lstrip("0")
1404 if not no_leading_zeros:
1405 prev_str = statement.bad_token.string
1406 bad_str = statement.next_token.string
1407 else:
1408 nb_zeros = len(statement.bad_token.string) - len(no_leading_zeros)
1409 prev_str = "0" * nb_zeros
1410 bad_str = statement.bad_token.string[nb_zeros:]
1411 else:
1412 prev_str = statement.prev_token.string
1413 bad_str = statement.bad_token.string
1414
1415 return _proper_decimal_or_octal_number(prev_str, bad_str)
1416
1417
1418 @add_python_message
1419 def mismatched_parenthesis(message: str = "", statement=None):
1420 pattern1 = re.compile(
1421 r"closing parenthesis '(.*)' does not match opening parenthesis '(.*)' on line (\d+)"
1422 )
1423 match = re.search(pattern1, message)
1424 if match is None:
1425 lineno = None
1426 pattern2 = re.compile(
1427 r"closing parenthesis '(.*)' does not match opening parenthesis '(.*)'"
1428 )
1429 match = re.search(pattern2, message)
1430 if match is None:
1431 return {}
1432 else:
1433 lineno = match[3]
1434
1435 opening = match[2]
1436 closing = match[1]
1437
1438 cause = statement_analyzer.mismatched_brackets(statement)
1439 if cause:
1440 return cause
1441
1442 debug_helper.log(
1443 "statement_analyzer.mismatched_brackets failed."
1444 ) # pragma: no cover
1445 if lineno is not None: # pragma: no cover
1446 cause = _(
1447 "Python tells us that the closing `{closing}` on the last line shown\n"
1448 "does not match the opening `{opening}` on line {lineno}.\n\n"
1449 ).format(closing=closing, opening=opening, lineno=lineno)
1450 else: # pragma: no cover
1451 cause = _(
1452 "Python tells us that the closing `{closing}` on the last line shown\n"
1453 "does not match the opening `{opening}`.\n\n"
1454 ).format(closing=closing, opening=opening)
1455
1456 return {"cause": cause} # pragma: no cover
1457
1458
1459 @add_python_message
1460 def named_arguments_must_follow_bare_star(message: str = "", _statement=None):
1461 # TODO: revise this as it can be greatly improved
1462 if message != "named arguments must follow bare *":
1463 return {}
1464
1465 hint = _("Did you forget something after `*`?\n")
1466 cause = _(
1467 "Assuming you were defining a function, you need\n"
1468 "to replace `*` by either `*arguments` or\n"
1469 "by `*, named_argument=value`.\n"
1470 )
1471 return {"cause": cause, "suggest": hint}
1472
1473
1474 @add_python_message
1475 def name_assigned_to_prior_global(message: str = "", statement=None):
1476 # something like: name 'p' is assigned to before global declaration
1477 if "is assigned to before global declaration" not in message:
1478 return {}
1479
1480 name = message.split("'")[1]
1481 cause = _(
1482 "You assigned a value to the variable `{name}`\n"
1483 "before declaring it as a global variable.\n"
1484 ).format(name=name)
1485 # Highlight global and variable name individually
1486 first, second = "", ""
1487 for tok in statement.tokens:
1488 if tok.string == "global":
1489 first = tok
1490 elif tok.string == name:
1491 second = tok
1492 break
1493 if first and second:
1494 statement.location_markers = su.highlight_two_tokens(first, second)
1495 return {"cause": cause}
1496
1497
1498 @add_python_message
1499 def name_assigned_to_prior_nonlocal(message: str = "", statement=None):
1500 # something like: name 'p' is assigned to before global declaration
1501 if "is assigned to before nonlocal declaration" not in message:
1502 return {}
1503
1504 name = message.split("'")[1]
1505 hint = _("Did you forget to add `nonlocal`?\n")
1506 cause = _(
1507 "You assigned a value to the variable `{name}`\n"
1508 "before declaring it as a nonlocal variable.\n"
1509 ).format(name=name)
1510 # Highlight nonlocal and variable name individually
1511 first, second = "", ""
1512 for tok in statement.tokens:
1513 if tok.string == "nonlocal":
1514 first = tok
1515 elif tok.string == name:
1516 second = tok
1517 break
1518
1519 if first and second:
1520 statement.location_markers = su.highlight_two_tokens(first, second)
1521 return {"cause": cause, "suggest": hint}
1522
1523
1524 @add_python_message
1525 def name_is_parameter_and_global(message: str = "", statement=None):
1526 # something like: name 'x' is parameter and global
1527 line = statement.entire_statement
1528 if "is parameter and global" not in message:
1529 return {}
1530
1531 name = message.split("'")[1]
1532 if name in line and "global" in line:
1533 newline = line
1534 else: # pragma: no cover
1535 debug_helper.log("New case for name_is_parameter_and_global")
1536 newline = f"global {name}"
1537 cause = _(
1538 "You are including the statement\n\n"
1539 " {newline}\n\n"
1540 "indicating that `{name}` is a variable defined outside a function.\n"
1541 "You are also using the same `{name}` as an argument for that\n"
1542 "function, thus indicating that it should be variable known only\n"
1543 "inside that function, which is the contrary of what `global` implied.\n"
1544 ).format(newline=newline, name=name)
1545 return {"cause": cause}
1546
1547
1548 @add_python_message
1549 def name_is_parameter_and_nonlocal(message: str = "", _statement=None):
1550 if "is parameter and nonlocal" not in message:
1551 return {}
1552
1553 name = message.split("'")[1]
1554 cause = _(
1555 "You used `{name}` as a parameter for a function\n"
1556 "before declaring it also as a nonlocal variable:\n"
1557 "`{name}` cannot be both at the same time.\n"
1558 ).format(name=name)
1559 return {"cause": cause}
1560
1561
1562 @add_python_message
1563 def name_used_prior_global(message: str = "", statement=None):
1564 # something like: name 'p' is used prior to global declaration
1565 if "is used prior to global declaration" not in message:
1566 return {}
1567
1568 name = message.split("'")[1]
1569 cause = _(
1570 "You used the variable `{name}`\nbefore declaring it as a global variable.\n"
1571 ).format(name=name)
1572 # Highlight global and variable name individually
1573 first, second = "", ""
1574 for tok in statement.tokens:
1575 if tok.string == "global":
1576 first = tok
1577 elif tok.string == name:
1578 second = tok
1579 break
1580
1581 if first and second:
1582 statement.location_markers = su.highlight_two_tokens(first, second)
1583 return {"cause": cause}
1584
1585
1586 @add_python_message
1587 def name_used_prior_nonlocal(message: str = "", statement=None):
1588 # something like: name 'q' is used prior to nonlocal declaration
1589 if "is used prior to nonlocal declaration" not in message:
1590 return {}
1591
1592 hint = _("Did you forget to write `nonlocal` first?\n")
1593 name = message.split("'")[1]
1594 cause = _(
1595 "You used the variable `{name}`\n"
1596 "before declaring it as a nonlocal variable.\n"
1597 ).format(name=name)
1598 # Highlight nonlocal and variable name individually
1599 first, second = "", ""
1600 for tok in statement.tokens:
1601 if tok.string == "nonlocal":
1602 first = tok
1603 elif tok.string == name:
1604 second = tok
1605 break
1606
1607 if first and second:
1608 statement.location_markers = su.highlight_two_tokens(first, second)
1609 return {"cause": cause, "suggest": hint}
1610
1611
1612 @add_python_message
1613 def no_binding_for_nonlocal(message: str = "", _statement=None):
1614 if "no binding for nonlocal" not in message:
1615 return {}
1616
1617 name = message.split("'")[1]
1618 cause = _(
1619 "You declared the variable `{name}` as being a\n"
1620 "nonlocal variable but it cannot be found.\n"
1621 ).format(name=name)
1622 return {"cause": cause}
1623
1624
1625 @add_python_message
1626 def nonlocal_at_module_level(message: str = "", _statement=None):
1627 if "nonlocal declaration not allowed at module level" not in message:
1628 return {}
1629 cause = _(
1630 "You used the nonlocal keyword at a module level.\n"
1631 "The nonlocal keyword refers to a variable inside a function\n"
1632 "given a value outside that function."
1633 )
1634 return {"cause": cause}
1635
1636
1637 @add_python_message
1638 def non_default_arg_follows_default_arg(message: str = "", _statement=None):
1639 if (
1640 "parameter without a default follows parameter with a default" not in message
1641 and "non-default argument follows default argument" not in message
1642 ):
1643 return {}
1644 cause = _(
1645 "In Python, you can define functions with only positional arguments\n\n"
1646 " def test(a, b, c): ...\n\n"
1647 "or only keyword arguments\n\n"
1648 " def test(a=1, b=2, c=3): ...\n\n"
1649 "or a combination of the two\n\n"
1650 " def test(a, b, c=3): ...\n\n"
1651 "but with the keyword arguments appearing after all the positional ones.\n"
1652 "According to Python, you used positional arguments after keyword ones.\n"
1653 )
1654 return {"cause": cause}
1655
1656
1657 @add_python_message
1658 def parens_around_exceptions(message: str = "", statement=None):
1659 # sourcery skip: merge-comparisons
1660 # keep in sync with statement_analyzer.parens_around_exceptions
1661 if message != "multiple exception types must be parenthesized":
1662 return {}
1663
1664 new_tokens = []
1665 paren_added = False
1666 for token in statement.tokens:
1667 if token == "except":
1668 new_tokens.extend([token, " ("])
1669 elif token == "as" or token == ":" and not paren_added:
1670 new_tokens.extend([" ) ", token])
1671 paren_added = True
1672 else:
1673 new_tokens.append(token)
1674 new_line = token_utils.untokenize(new_tokens)
1675 if not fixers.check_statement(new_line):
1676 new_line = ""
1677 else:
1678 new_line = f"\n {new_line.lstrip()}\n"
1679
1680 hint = _("Did you forget parentheses?\n")
1681 cause = _(
1682 "I am guessing that you wanted to use an `except` statement\n"
1683 "with multiple exception types. If that is the case, you must\n"
1684 "surround them with parentheses.\n"
1685 )
1686 return {"cause": cause + new_line, "suggest": hint}
1687
1688
1689 @add_python_message
1690 def positional_argument_follows_keyword_arg(message: str = "", _statement=None):
1691 if "positional argument follows keyword argument" not in message:
1692 return {}
1693 cause = _(
1694 "In Python, you can call functions with only positional arguments\n\n"
1695 " test(1, 2, 3)\n\n"
1696 "or only keyword arguments\n\n"
1697 " test(a=1, b=2, c=3)\n\n"
1698 "or a combination of the two\n\n"
1699 " test(1, 2, c=3)\n\n"
1700 "but with the keyword arguments appearing after all the positional ones.\n"
1701 "According to Python, you used positional arguments after keyword ones.\n"
1702 )
1703 return {"cause": cause}
1704
1705
1706 @add_python_message
1707 def python2_print(message: str = "", statement=None):
1708 if not message.startswith(
1709 "Missing parentheses in call to 'print'. Did you mean print("
1710 ):
1711 return {}
1712
1713 content = statement.entire_statement.replace("print", "", 1).strip()
1714 possible_statement = f"print({content})"
1715 valid = fixers.check_statement(possible_statement)
1716 if "\n" in content or len(content) > 40 or not valid:
1717 message = "..."
1718 else:
1719 message = content
1720 cause = _(
1721 "Perhaps you need to type\n\n"
1722 " print({message})\n\n"
1723 "In older version of Python, `print` was a keyword.\n"
1724 "Now, `print` is a function; you need to use parentheses to call it.\n"
1725 ).format(message=message)
1726 if not valid:
1727 cause += _("Note that arguments of `print` must be separated by commas.\n")
1728 hint = _("Did you mean `print({message})`?\n").format(message=message)
1729 return {"cause": cause, "suggest": hint}
1730
1731
1732 @add_python_message
1733 def return_outside_function(message: str = "", _statement=None):
1734 if message != "'return' outside function":
1735 return {}
1736
1737 cause = _("You can only use a `return` statement inside a function or method.\n")
1738 return {"cause": cause}
1739
1740
1741 @add_python_message
1742 def star_assignment_target_must_be_list(message: str = "", _statement=None):
1743 if message != "starred assignment target must be in a list or tuple":
1744 return {}
1745
1746 cause = _(
1747 "A star assignment must be of the form:\n\n ... *name = list_or_tuple\n\n"
1748 )
1749 return {"cause": cause}
1750
1751
1752 @add_python_message
1753 def starred_expression_in_dict_value(message: str = "", statement=None):
1754 if message != "cannot use a starred expression in a dictionary value":
1755 return {}
1756 cause = _(
1757 "It looks like you tried to use a starred expression as a dict value;\n"
1758 "this is not allowed.\n"
1759 )
1760 if statement.bad_token == "*":
1761 bad_token = statement.bad_token
1762 else:
1763 return {"cause": cause}
1764 # Before we make any attempt at modifying the original code,
1765 # we make sure that our statement checker can properly identify that
1766 # the original code is invalid. See #205
1767 if fixers.check_statement(statement.bad_line):
1768 return {"cause": cause}
1769
1770 new_statement = fixers.replace_token(statement.statement_tokens, bad_token, "")
1771 if fixers.check_statement(new_statement):
1772 cause += "\n" + _(
1773 "The following statement has no syntax error:\n\n {statement}\n"
1774 ).format(statement=new_statement)
1775 return {"cause": cause}
1776
1777
1778 @add_python_message
1779 def too_many_nested_blocks(message: str = "", _statement=None):
1780 if message != "too many statically nested blocks":
1781 return {}
1782
1783 cause = _(
1784 "Your code is too complex for Python:\n"
1785 "you need to reduce the number of indented code blocks\n"
1786 "contained inside other code blocks.\n"
1787 )
1788 return {"cause": cause}
1789
1790
1791 @add_python_message
1792 def too_many_nested_parenthesis(message: str = "", _statement=None):
1793 if message != "too many nested parentheses": # python 3.89+
1794 return {}
1795
1796 cause = _(
1797 "Your code is too complex for Python:\n"
1798 "you need to reduce the number of parentheses\n"
1799 "contained inside other parentheses.\n"
1800 )
1801 return {"cause": cause}
1802
1803
1804 @add_python_message
1805 def trailing_comma_not_allowed(message: str = "", statement=None):
1806 # As far as I know, this is only in import statement; for example:
1807 # from math import sin, cos,
1808 if message != "trailing comma not allowed without surrounding parentheses":
1809 return {}
1810
1811 cause = _(
1812 "Python indicates that you need to surround an expression\n"
1813 "ending with a comma by parentheses.\n"
1814 )
1815 no_additional_suggestion = _(
1816 "I have no additional suggestion to offer.\n"
1817 "Please feel free to report this case.\n"
1818 )
1819 # Before we make any attempt at modifying the original code,
1820 # we make sure that our statement checker can properly identify that
1821 # the original code is invalid. See #205
1822 if fixers.check_statement(statement.bad_line):
1823 return {"cause": cause + no_additional_suggestion}
1824
1825 perhaps_new_statement = lambda: _( # noqa
1826 "Perhaps you meant to write\n\n`{new_statement}`\n"
1827 )
1828
1829 bad_token = statement.bad_token
1830 if bad_token.is_keyword():
1831 new_statement = fixers.replace_token(statement.statement_tokens, bad_token, "")
1832 if fixers.check_statement(new_statement):
1833 cause += _(
1834 "However, I suspect that you wrote the keyword `{boolean}` by mistake.\n"
1835 ).format(boolean=bad_token)
1836 if bad_token.string in ["and", "or"]:
1837 cause += _(
1838 "The Python keyword `{boolean}` can only be used for boolean expressions.\n"
1839 ).format(boolean=bad_token) + perhaps_new_statement().format(
1840 new_statement=new_statement
1841 )
1842 else:
1843 cause += perhaps_new_statement().format(new_statement=new_statement)
1844 return {"cause": cause}
1845 elif bad_token == ",": # Python 3.9+
1846 new_statement = fixers.replace_token(statement.statement_tokens, bad_token, "")
1847 if fixers.check_statement(new_statement):
1848 hint = _("Did you write a comma by mistake?\n")
1849 cause += _(
1850 "However, if you remove the last comma, there will be no syntax error.\n"
1851 )
1852 cause += perhaps_new_statement().format(new_statement=new_statement)
1853 return {"cause": cause, "suggest": hint}
1854 elif (
1855 statement.last_token == ","
1856 ): # Python 3.6 - 3.8 (bad_token is at beginning of items)
1857 new_statement = fixers.replace_token(
1858 statement.statement_tokens, statement.last_token, ""
1859 )
1860 if fixers.check_statement(new_statement):
1861 hint = _("Did you write a comma by mistake?\n")
1862 cause += _(
1863 "However, if you remove the last comma, there will be no syntax error.\n"
1864 )
1865 cause += perhaps_new_statement().format(new_statement=new_statement)
1866 return {"cause": cause, "suggest": hint}
1867
1868 debug_helper.log("new case to consider.")
1869 return {"cause": cause + no_additional_suggestion}
1870
1871
1872 @add_python_message
1873 def unexpected_character_after_continuation(message: str = "", statement=None):
1874 if "unexpected character after line continuation character" not in message:
1875 return {}
1876
1877 cause = _(
1878 "You are using the continuation character `\\` outside of a string,\n"
1879 "and it is followed by some other character(s).\n"
1880 )
1881 bad_token = statement.bad_token
1882 prev_token = statement.prev_token
1883 marked_token = token_utils.clone(bad_token)
1884 real_bad_line = statement.original_bad_line.rstrip("\n")
1885 remainder = ""
1886
1887 if statement.prev_token != "\\":
1888 # Starting with Python 3.9, the new peg parser is
1889 # not giving us the correct location for the error; so we need to find it.
1890 # The situation gets worse starting with Python 3.12 as the tokenizer
1891 # keeps only the tokens that occur before the continuation character.
1892 #
1893 # We use a simple strategy of removing the tokens one-by-one from
1894 # the beginning of the line until we find the continuation character.
1895 # We then remove that character (and leading spaces), tokenize
1896 # the remaining line: the first token is the one that is desired.
1897 if statement.tokens:
1898 prev_token = statement.tokens[-1]
1899 found_continuation = False
1900 bad_line = statement.original_bad_line
1901
1902 for token in statement.tokens:
1903 if bad_line and bad_line[0] == "\\":
1904 remainder = bad_line = bad_line[1:]
1905 new_tokens = token_utils.tokenize(bad_line)
1906 if new_tokens:
1907 bad_token = new_tokens[0]
1908 found_continuation = True
1909 break
1910 break
1911 bad_line = bad_line.replace(token.string, "", 1).lstrip()
1912
1913 if not found_continuation: # Python 3.12 ... not enough tokens
1914 if bad_line and bad_line[0] == "\\":
1915 remainder = bad_line = bad_line[1:]
1916 bad_line = bad_line.replace("\\", "", 1).lstrip()
1917 new_tokens = token_utils.tokenize(bad_line[1:])
1918 if new_tokens:
1919 bad_token = new_tokens[0]
1920 found_continuation = True
1921 if not found_continuation: # pragma: no cover
1922 debug_helper.log("Could not find bad token after continuation character.")
1923 elif prev_token:
1924 remainder = remainder.rstrip("\n")
1925 marked_token.start_col = len(real_bad_line) - len(remainder)
1926 marked_token.string = remainder
1927 statement.location_markers = su.highlight_single_token(marked_token)
1928 else:
1929 if prev_token:
1930 remainder = remainder.rstrip("\n")
1931 marked_token.start_col = prev_token.end_col
1932 marked_token.string = marked_token.line[marked_token.start_col :]
1933 statement.location_markers = su.highlight_single_token(marked_token)
1934
1935 if bad_token.is_number(): # something like 3 \ 4 instead of 3 / 4
1936 number = bad_token.string
1937 statement.location_markers = su.highlight_single_token(bad_token)
1938 cause += _(
1939 "I am guessing that you wanted to divide by the number {number} \n"
1940 "and wrote \\ instead of /."
1941 ).format(number=number)
1942 hint = _("Did you mean to divide by {number}?\n").format(number=number)
1943 return {"cause": cause, "suggest": hint}
1944
1945 cause += _("I am guessing that you forgot to enclose some content in a string.\n")
1946 return {"cause": cause}
1947
1948
1949 @add_python_message
1950 def unexpected_eof_while_parsing(message: str = "", statement=None):
1951 if "unexpected EOF while parsing" not in message:
1952 return {}
1953
1954 cause = _(
1955 "Python tells us that it reached the end of the file\n"
1956 "and expected more content.\n\n"
1957 )
1958 additional_cause = statement_analyzer.unclosed_bracket(statement)
1959 if additional_cause:
1960 cause += (
1961 _("I will attempt to be give a bit more information.\n\n")
1962 + additional_cause["cause"]
1963 )
1964 return {"cause": cause}
1965
1966
1967 @add_python_message
1968 def unicode_error(message: str = "", _statement=None):
1969 if "unicode error" not in message or "truncated \\UXX" not in message:
1970 return {}
1971 hint = _("Perhaps you need to double the backslash characters.\n")
1972 cause = _(
1973 "I suspect that you wrote a string that contains\n"
1974 "one backslash character, `\\` followed by an uppercase `U`\n"
1975 "and some more characters.\n"
1976 "Python likely interpreted this as indicating the beginning of\n"
1977 "what is known as an escape sequence for special unicode characters.\n"
1978 "To solve the problem, either write a so-called 'raw string'\n"
1979 "by adding the letter `r` as a prefix in\n"
1980 "front of the string, or replace `\\U`, by `\\\\U`.\n"
1981 )
1982 return {"cause": cause, "suggest": hint}
1983
1984
1985 @add_python_message
1986 def unmatched_parenthesis(message: str = "", statement=None):
1987 # Python 3.8
1988 if message == "unmatched ')'":
1989 bracket = su.name_bracket(")")
1990 elif message == "unmatched ']'":
1991 bracket = su.name_bracket("]")
1992 elif message == "unmatched '}'":
1993 bracket = su.name_bracket("}")
1994 else:
1995 return {}
1996 cause = _(
1997 "The closing {bracket} on line {linenumber} does not match anything.\n"
1998 ).format(bracket=bracket, linenumber=statement.linenumber)
1999 return {"cause": cause}
2000
2001
2002 @add_python_message
2003 def unterminated_f_string(message: str = "", statement=None):
2004 if not (
2005 "f-string: unterminated string" in message
2006 or "unterminated string literal" in message
2007 ):
2008 return {}
2009
2010 hint = _("Perhaps you forgot a closing quote.\n")
2011 # Depending on the Python version, the error points at the f-string itself
2012 # or the previous or the next token. We must guard against the case where
2013 # someone writes three strings in a row.
2014 for tok in [statement.prev_token, statement.bad_token, statement.next_token]:
2015 # escaped quotes are not allowed in f-strings, so we can simply count the number
2016 # of quotes of both kinds and look for an odd-number.
2017 if tok.is_f_string():
2018 fstring = tok
2019 break
2020 else: # pragma: no cover
2021 debug_helper.log("Need to record case in unterminated_f_string")
2022 fstring = "<not found>"
2023 cause = _(
2024 "Inside the f-string `{fstring}`, \n"
2025 "you have another string, which starts with either a\n"
2026 "single quote (') or double quote (\"), without a matching closing one.\n"
2027 ).format(fstring=fstring)
2028 return {"cause": cause, "suggest": hint}
2029
2030
2031 @add_python_message
2032 def yield_outside_function(message: str = "", _statement=None):
2033 if message != "'yield' outside function":
2034 return {}
2035
2036 cause = _("You can only use a `yield` statement inside a function.\n")
2037 return {"cause": cause}
2038
2039
2040 @add_python_message
2041 def you_found_it(message: str = "", statement=None): # pragma: no cover
2042 if message != "You found it!" or statement.bad_token != "__peg_parser__":
2043 return {}
2044
2045 cause = _(
2046 "This is a message that was added in Python 3.9\n"
2047 "to prevent redefining `__peg_parser__`.\n"
2048 "It should not be present in other versions.\n"
2049 )
2050 return {"cause": cause}
2051
2052
2053 # Generic cases not covered in previous specific ones.
2054
2055
2056 @add_python_message
2057 def cannot_delete_something_else(message: str = "", _statement=None):
2058 return {"cause": _can_only_delete()} if message.startswith("cannot delete") else {}
2059
2060
2061 @add_python_message
2062 def assign_to_others(message: str = "", _statement=None):
2063 if not message.startswith("cannot assign to"):
2064 return {}
2065 hint = _assign_to_identifiers_only()
2066 return {"cause": hint, "suggest": hint}
2067
2068
2069 @add_python_message
2070 def arguments_cannot_follow_var(message: str = "", statement=None):
2071 # new message for Python 3.11
2072 if "arguments cannot follow var-keyword argument" not in message:
2073 return {}
2074 return error_in_def.analyze_def_statement(statement)
2075
2076
2077 @add_python_message
2078 def slash_must_be_ahead(message: str = "", statement=None):
2079 # new message for Python 3.11
2080 if "/ must be ahead of *" not in message:
2081 return {}
2082 return error_in_def.analyze_def_statement(statement)
2083
2084
2085 @add_python_message
2086 def star_may_appear_only_once(message: str = "", statement=None):
2087 # new message for Python 3.11
2088 if "* argument may appear only once" not in message:
2089 return {}
2090 return error_in_def.analyze_def_statement(statement)
2091
2092
2093 @add_python_message
2094 def slash_must_appear_only_once(message: str = "", statement=None):
2095 # new message for Python 3.11
2096 if "/ may appear only once" not in message:
2097 return {}
2098 return error_in_def.analyze_def_statement(statement)
2099
2100
2101 @add_python_message
2102 def invalid_non_printable_character(message: str = "", statement=None):
2103 # new message for Python 3.11
2104 if "invalid non-printable character" not in message:
2105 return {}
2106
2107 problem = _(
2108 "Friendly-traceback cannot identify the non-printable character.\n"
2109 "This should not happen. Please report this case"
2110 )
2111
2112 char = statement.bad_token.string # 3.11
2113 prev = statement.prev_token.string # 3.12
2114 if token_utils.is_invisible_control_character(prev) == prev:
2115 char = prev
2116
2117 if len(char) != 1:
2118 return {"cause": problem + "\n not len(char)==1"}
2119 if token_utils.is_invisible_control_character(char) != char:
2120 return {"cause": problem + "\n is_invisible_control_character(char) != char"}
2121
2122 return {
2123 "cause": _(
2124 "Your code contains the invalid non-printable character {char}.\n"
2125 ).format(char=repr(char))
2126 }
2127
2128
2129 @add_python_message
2130 def import_from(message: str = "", statement=None):
2131 # new message for Python 3.12
2132 if message != "Did you mean to use 'from ... import ...' instead?":
2133 return {}
2134 for token in statement.tokens:
2135 if token == "from":
2136 bad_token = token
2137 break
2138 statement.location_markers = su.highlight_two_tokens(statement.tokens[0], bad_token)
2139 bad_line = statement.bad_line.replace("import ", "").strip()
2140 function, module = bad_line.split(" from ")
2141 new_line = f"from {module} import {function}"
2142 if not fixers.check_statement(new_line):
2143 function = module = "(...)"
2144
2145 hint = _("Did you mean `from {module} import {function}`?\n").format(
2146 module=module.strip(), function=function.strip()
2147 )
2148 cause = _(
2149 "You wrote something like\n\n"
2150 " import {function} from {module}\n\n"
2151 "instead of\n\n"
2152 " from {module} import {function}\n\n"
2153 ).format(module=module.strip(), function=function.strip())
2154 return {"cause": cause, "suggest": hint}
2155
2156
2157 @add_python_message
2158 def incomplete_input(message: str = "", statement=None):
2159 # This can occur when using code.interact() which is used
2160 # by IDLE and the friendly console
2161 # Note: there are no unit tests for this.
2162 if message != "incomplete input":
2163 return {}
2164 try:
2165 compile(statement.bad_line, "<dummy>", "single")
2166 except SyntaxError as exc:
2167 cause = _("The statement `{line}` is not valid.\n\n").format(
2168 line=statement.bad_line
2169 )
2170 if exc.msg == "incomplete input":
2171 cause += _("I don't have any additional information")
2172 return {"cause": cause}
2173 for case in MESSAGE_ANALYZERS:
2174 original_cause = case(exc.msg, statement)
2175 if original_cause:
2176 cause += original_cause["cause"]
2177 break
2178 else:
2179 cause += _("I don't have any additional information")
2180 return {"cause": cause}
2181 return {}