Debian Codegraph @

friendly_traceback/syntax_errors/error_in_def.py

raw symbols SCIP
1 # type: ignore
2 """In this module, we try to identify a remedy to a syntax error
3 associated with a 'def' statement.
4 """
5 import platform
6 import sys
7
8 from .. import debug_helper, utils
9 from ..ft_gettext import current_lang, internal_error
10 from . import fixers
11 from . import syntax_utils as su
12
13 STATEMENT_ANALYZERS = []
14 _ = current_lang.translate
15 ASYNC = 0
16
17
18 def more_errors():
19 return "\n" + _(
20 "However, making such a change would still not correct\n"
21 "all the syntax errors in the code you wrote.\n"
22 )
23
24
25 def def_correct_syntax():
26 async_ = "" if ASYNC == 0 else "async "
27 # fmt: off
28 return _(
29 "The correct syntax is:\n\n"
30 " {async_}def name ( ... ):"
31 ).format(async_=async_) + "\n"
32 # fmt: on
33
34
35 def add_statement_analyzer(func):
36 """A simple decorator that adds a function to the list
37 of all functions that analyze a single statement."""
38 STATEMENT_ANALYZERS.append(func)
39
40
41 # ========================================================
42 # Main calling function
43 # ========================================================
44
45
46 def analyze_def_statement(statement):
47 """Analyzes the statement as identified by Python as that
48 on which the error occurred."""
49 global ASYNC
50 if not statement.tokens: # pragma: no cover
51 debug_helper.log("Statement with no tokens in error_in_def.py")
52 return {"cause": internal_error("No tokens")}
53
54 ASYNC = 0
55 if statement.tokens[0] == "async":
56 ASYNC = 1
57
58 if len(statement.tokens) > 1 + ASYNC and str(statement.tokens[1 + ASYNC]) in (
59 "=",
60 ":=",
61 ):
62 # Let the generic method handle the wrong assignment case
63 return {}
64
65 for analyzer in STATEMENT_ANALYZERS:
66 cause = analyzer(statement)
67 if cause:
68 return cause
69 return {}
70
71
72 @add_statement_analyzer
73 def def_begin_code_block(statement): #
74 # Thinking of trying to use def to begin a code block, i.e.
75 # def : ...
76 if statement.nb_tokens > 2 + ASYNC or statement.bad_token != ":":
77 return {}
78
79 if statement.first_token.start_col == 0:
80 hint = _("A function needs a name.\n")
81 cause = _(
82 "You tried to define a function and did not use the correct syntax.\n"
83 )
84 else:
85 hint = _("Functions and methods need a name.\n")
86 cause = _(
87 "You tried to define a function or method and did not use the correct syntax.\n"
88 )
89
90 return {"cause": cause + def_correct_syntax(), "suggest": hint}
91
92
93 @add_statement_analyzer
94 def missing_parens(statement):
95 # Something like
96 # def test: ...
97 if (
98 statement.bad_token != ":"
99 and statement.nb_tokens >= 3 + ASYNC
100 and statement.bad_token != statement.tokens[2 + ASYNC]
101 ):
102 return {}
103
104 # Before we make any attempt at modifying the original code,
105 # we make sure that our statement checker can properly identify that
106 # the original code is invalid. See #205
107 if fixers.check_statement(statement.bad_line):
108 return {}
109
110 new_statement = fixers.replace_token(
111 statement.statement_tokens,
112 statement.bad_token,
113 "()" + statement.bad_token.string,
114 )
115 if fixers.check_statement(new_statement):
116 hint = _("Did you forget parentheses?\n")
117 cause = _(
118 "Perhaps you forgot to include parentheses.\n"
119 "You might have meant to write\n\n"
120 " {line}\n"
121 ).format(line=new_statement)
122 return {"cause": cause, "suggest": hint}
123
124 return {}
125
126
127 @add_statement_analyzer
128 def missing_parens_2(statement):
129 # Something like
130 # def test a, b:
131 if statement.bad_token_index != 2 + ASYNC and statement.last_token != ":":
132 return {}
133 # Before we make any attempt at modifying the original code,
134 # we make sure that our statement checker can properly identify that
135 # the original code is invalid. See #205
136 if fixers.check_statement(statement.bad_line):
137 return {}
138
139 new_statement = fixers.replace_two_tokens(
140 statement.statement_tokens,
141 statement.bad_token,
142 first_string="(" + statement.bad_token.string,
143 second_token=statement.last_token,
144 second_string="):",
145 )
146 if fixers.check_statement(new_statement):
147 hint = _("Did you forget parentheses?\n")
148 cause = _(
149 "Perhaps you forgot to include parentheses.\n"
150 "You might have meant to write\n\n"
151 " {line}\n"
152 ).format(line=new_statement)
153 return {"cause": cause, "suggest": hint}
154
155 return {}
156
157
158 @add_statement_analyzer
159 def missing_colon(statement):
160 """look for missing colon at the end of statement; includes the case where
161 something else has been written as a typo."""
162 if (
163 statement.last_token == ":"
164 or statement.bad_token != statement.last_token
165 or statement.statement_brackets
166 ):
167 return {}
168
169 # Before we make any attempt at modifying the original code,
170 # we make sure that our statement checker can properly identify that
171 # the original code is invalid. See #205
172 if fixers.check_statement(statement.bad_line):
173 return {}
174
175 cause = _("A function definition statement must end with a colon.\n")
176
177 new_statement = fixers.replace_token(
178 statement.statement_tokens, statement.bad_token, ":"
179 )
180 if fixers.check_statement(new_statement):
181 hint = _("Did you forget to write a colon?\n")
182 cause += _("You wrote `{bad}` instead of a colon.\n").format(
183 bad=statement.bad_token
184 )
185 return {"cause": cause, "suggest": hint}
186
187 new_statement = fixers.replace_token(
188 statement.statement_tokens, statement.bad_token, " "
189 )
190 if fixers.check_statement(new_statement):
191 hint = _("Did you write something by mistake after the colon?\n")
192 cause += _("A block of code must come after the colon.\n")
193 cause += _("Removing `{bad}`, might fix the problem.\n").format(
194 bad=statement.bad_token
195 )
196 return {"cause": cause, "suggest": hint}
197
198 new_statement = fixers.replace_token(
199 statement.statement_tokens,
200 statement.bad_token,
201 statement.bad_token.string + ":",
202 )
203 if fixers.check_statement(new_statement):
204 statement.location_markers = su.highlight_added_token(statement.bad_token, ":")
205 hint = _("Did you forget to write a colon?\n")
206 return {"cause": cause, "suggest": hint}
207
208 return {}
209
210
211 @add_statement_analyzer
212 def keyword_as_function_name(statement):
213 # Something like
214 # def pass(): ...
215 def_token = statement.tokens[ASYNC]
216 if not (statement.bad_token.is_keyword() and statement.prev_token == def_token):
217 return {}
218
219 # Before we make any attempt at modifying the original code,
220 # we make sure that our statement checker can properly identify that
221 # the original code is invalid. See #205
222 if fixers.check_statement(statement.bad_line):
223 return {}
224
225 hint = _("You cannot use a Python keyword as a function name.\n")
226 cause = _(
227 "You tried to use the Python keyword `{kwd}` as a function name.\n"
228 ).format(kwd=statement.bad_token)
229
230 new_statement = fixers.replace_token(
231 statement.statement_tokens, statement.bad_token, "name"
232 )
233 if not fixers.check_statement(new_statement):
234 cause += "\n" + _("There are more syntax errors later in your code.\n")
235
236 return {"cause": cause, "suggest": hint}
237
238
239 @add_statement_analyzer
240 def other_invalid_function_names(statement):
241 def_token = statement.tokens[ASYNC]
242 if statement.bad_token.is_identifier() or not (statement.prev_token == def_token):
243 return {}
244
245 # Before we make any attempt at modifying the original code,
246 # we make sure that our statement checker can properly identify that
247 # the original code is invalid. See #205
248 if fixers.check_statement(statement.bad_line):
249 return {}
250
251 new_statement = fixers.replace_token(
252 statement.statement_tokens, statement.bad_token, "name"
253 )
254 if not fixers.check_statement(new_statement):
255 return {}
256
257 hint = _("You wrote an invalid function name.\n")
258 cause = _(
259 "The name of a function must be a valid Python identifier,\n"
260 "that is a name that begins with a letter or an underscore character, `_`,\n"
261 "and which contains only letters, digits or the underscore character.\n"
262 )
263 if statement.bad_token.is_string():
264 cause += _("You attempted to use a string as a function name.\n")
265 hint = cause
266 return {"cause": cause, "suggest": hint}
267
268
269 @add_statement_analyzer
270 def function_definition_missing_name(statement):
271 def_token = statement.tokens[ASYNC]
272 if not (
273 def_token == "def"
274 and statement.bad_token == "("
275 and statement.prev_token == def_token
276 ):
277 return {}
278
279 # Before we make any attempt at modifying the original code,
280 # we make sure that our statement checker can properly identify that
281 # the original code is invalid. See #205
282 if fixers.check_statement(statement.bad_line):
283 return {}
284
285 cause = _("You forgot to name your function.\n")
286
287 new_statement = fixers.replace_token(
288 statement.tokens, statement.bad_token, "name ("
289 )
290 if fixers.check_statement(new_statement):
291 return {"cause": cause + def_correct_syntax()}
292
293 cause += _("However, there are some other syntax errors in your code.\n")
294 return {"cause": cause + def_correct_syntax()}
295
296
297 @add_statement_analyzer
298 def keyword_not_allowed_as_function_argument(statement):
299 if not (statement.bad_token.is_keyword() and statement.begin_brackets):
300 return {}
301
302 # Before we make any attempt at modifying the original code,
303 # we make sure that our statement checker can properly identify that
304 # the original code is invalid. See #205
305 if fixers.check_statement(statement.bad_line):
306 return {}
307
308 new_statement = fixers.replace_token(
309 statement.statement_tokens, statement.bad_token, "name"
310 )
311 if not fixers.check_statement(new_statement):
312 return {}
313
314 cause = _(
315 "I am guessing that you tried to use the Python keyword\n"
316 "`{kwd}` as an argument in the definition of a function\n"
317 "where an identifier (variable name) was expected.\n"
318 ).format(kwd=statement.bad_token)
319
320 return {"cause": cause}
321
322
323 @add_statement_analyzer
324 def dotted_name_not_allowed(statement):
325 if not (statement.bad_token == "." and statement.prev_token.is_identifier()):
326 return {}
327
328 if statement.bad_token_index > 3 + ASYNC:
329 cause = _("You cannot use dotted names as function arguments.\n")
330 if statement.next_token.is_identifier():
331 cause += _("Perhaps you meant to write a comma.\n")
332 hint = _("Did you mean to write a comma?\n")
333 else:
334 hint = cause
335 else:
336 hint = cause = _("You cannot use dots in function names.\n")
337 return {"cause": cause, "suggest": hint}
338
339
340 @add_statement_analyzer
341 def positional_arguments_in_def(statement):
342 if statement.bad_token != "/" or statement.prev_token.string not in "(,":
343 return {}
344
345 meaning = _(
346 "`/` indicates that the previous arguments in a function definition\n"
347 "are positional arguments.\n"
348 )
349
350 if sys.version_info < (3, 8):
351 hint = _(
352 "Function definitions cannot include the symbol `/` in this Python version.\n"
353 )
354 cause = meaning + _(
355 "This symbol can only be used with Python versions 3.8.0 or newer.\n"
356 "You are using Python version {version}.\n"
357 ).format(version=platform.python_version())
358 return {"cause": cause, "suggest": hint}
359
360 prev_tok = ""
361 for tok in statement.tokens[ASYNC : statement.bad_token_index]:
362 if tok == "**":
363 cause = meaning + _(
364 "You have unspecified keyword arguments that appear before\n"
365 "the symbol `/`.\n"
366 )
367 hint = _("Keyword arguments must appear after the `/` symbol.\n") # yes
368 return {"cause": cause, "suggest": hint}
369
370 if prev_tok == "*": # might be incorrect if used in *args
371 if tok == ",":
372 cause = meaning + _(
373 "However, `*` indicates that the arguments\n"
374 "that follow must be keyword arguments.\n"
375 "When they are used together, `/` must appear before `*`.\n"
376 )
377 hint = _("`*` must appear after `/` in a function definition.\n")
378 else:
379 hint = _(
380 "`*{name}` must appear after `/` in a function definition.\n"
381 ).format(name=tok.string)
382 cause = meaning + hint
383 return {"cause": cause, "suggest": hint}
384
385 if tok == "/" and prev_tok == ",":
386 cause = _("You can only use `/` once in a function definition.\n")
387 return {"cause": cause, "suggest": cause}
388
389 prev_tok = tok
390
391 return {}
392
393
394 @add_statement_analyzer
395 def keyword_arguments_in_def(statement):
396 if statement.bad_token != "*" or statement.prev_token != ",":
397 return {}
398
399 args = statement.next_token if statement.next_token.is_identifier() else ""
400 hint = _("You can only use `*` once in a function definition.\n")
401 tokens = statement.tokens
402 for index, tok in enumerate(tokens[ASYNC : statement.bad_token_index]):
403 next_token = tokens[index + 1]
404 if tok == "*":
405 if next_token.is_identifier() and args:
406 cause = hint + _(
407 "You have used it twice, with `*{first}` and `*{second}`.\n"
408 ).format(first=next_token, second=args)
409 return {"cause": cause, "suggest": hint}
410 elif next_token.is_identifier():
411 args = next_token.string
412
413 if args:
414 cause = hint + _(
415 "It must either be used by itself, `*`,\n"
416 "or in the form `*{args}`, but not both.\n"
417 ).format(args=args)
418 else:
419 cause = hint
420 return {"cause": cause, "suggest": hint}
421 elif tok == "**":
422 if args:
423 cause = _("`*{args}` must appear before `**{kwargs}`.\n").format(
424 args=args, kwargs=next_token
425 )
426 else:
427 cause = _("`**{kwargs}` must appear after the `*` operator.\n").format(
428 kwargs=next_token
429 )
430 return {"cause": cause, "suggest": hint}
431
432 debug_helper.log("New case to consider for * as bad token.") # pragma: no cover
433 return {"cause": hint, "suggest": hint} # pragma: no cover
434
435
436 @add_statement_analyzer
437 def number_as_argument(statement):
438 if not (statement.bad_token.is_number() and statement.prev_token.string in "(,"):
439 return {}
440
441 hint = _("You cannot use numbers as function arguments.\n")
442 cause = _(
443 "You used a number as an argument when defining a function.\n"
444 "You can only use identifiers (variable names) as function arguments.\n"
445 )
446 return {"cause": cause, "suggest": hint}
447
448
449 @add_statement_analyzer
450 def string_as_argument(statement):
451 if not (statement.bad_token.is_string() and statement.prev_token.string in "(,"):
452 return {}
453
454 hint = _("You cannot use strings as function arguments.\n")
455 cause = _(
456 "You used a string as an argument when defining a function.\n"
457 "You can only use identifiers (variable names) as function arguments.\n"
458 )
459 return {"cause": cause, "suggest": hint}
460
461
462 @add_statement_analyzer
463 def tuple_as_argument(statement):
464 if statement.bad_token != "(" or statement.prev_token.string not in "(,":
465 return {}
466
467 hint = _("You cannot have explicit tuples as function arguments.\n")
468
469 cause = hint + _(
470 "You can only use identifiers (variable names) as function arguments.\n"
471 "Assign any tuple to a parameter and unpack it\n"
472 "within the body of the function.\n"
473 )
474 return {"cause": cause, "suggest": hint}
475
476
477 @add_statement_analyzer
478 def list_as_argument(statement):
479 if statement.bad_token != "[" or statement.prev_token.string not in "(,":
480 return {}
481
482 hint = _("You cannot have explicit lists as function arguments.\n")
483 cause = hint + _(
484 "You can only use identifiers (variable names) as function arguments.\n"
485 )
486 return {"cause": cause, "suggest": hint}
487
488
489 @add_statement_analyzer
490 def dict_or_set_as_argument(statement):
491 if statement.bad_token != "{" or statement.prev_token.string not in "(,":
492 return {}
493
494 hint = _("You cannot have any explicit dict or set as function arguments.\n")
495 cause = hint + _(
496 "You can only use identifiers (variable names) as function arguments.\n"
497 )
498 return {"cause": cause, "suggest": hint}
499
500
501 @add_statement_analyzer
502 def operator_as_argument(statement):
503 """This looks at various possible fixes when the bad token is an operator.
504 The following cases are considered:
505 1. operator instead of comma
506 2. operator instead of equal sign
507 """
508 if not statement.bad_token.is_operator() or statement.prev_token == "def":
509 return {}
510
511 # Before we make any attempt at modifying the original code,
512 # we make sure that our statement checker can properly identify that
513 # the original code is invalid. See #205
514 if fixers.check_statement(statement.bad_line):
515 return {}
516
517 no_op = _("You cannot have operators as function arguments.\n")
518
519 # def test(a+b): -> def test(a, b):
520 new_statement = fixers.replace_token(
521 statement.statement_tokens, statement.bad_token, ","
522 )
523 if fixers.check_statement(new_statement):
524 hint = _("Did you mean to write a comma?\n")
525 cause = no_op + _(
526 "I suspect you made a typo and wrote `{op}` instead of a comma.\n"
527 "The following statement contains no syntax error:\n\n"
528 " {new_statement}"
529 ).format(op=statement.bad_token, new_statement=new_statement)
530 return {"cause": cause, "suggest": hint}
531
532 # def test(a=1, b+2): -> def test(a=1, b=2):
533 new_statement = fixers.replace_token(
534 statement.statement_tokens, statement.bad_token, "="
535 )
536 if fixers.check_statement(new_statement):
537 hint = _("Did you mean to write an equal sign?\n")
538 cause = no_op + _(
539 "I suspect you made a typo and wrote `{op}` instead of an equal sign.\n"
540 "The following statement contains no syntax error:\n\n"
541 " {new_statement}"
542 ).format(op=statement.bad_token, new_statement=new_statement)
543 return {"cause": cause, "suggest": hint}
544
545 # def test(a,,b): -> def test(a,b):
546 new_statement = fixers.replace_token(
547 statement.statement_tokens, statement.bad_token, ""
548 )
549 if fixers.check_statement(new_statement):
550 hint = _("Did you mean to write `{op}`?\n").format(op=statement.bad_token)
551 cause = _(
552 "I suspect you made a typo and added `{op}` by mistake.\n"
553 "The following statement contains no syntax error:\n\n"
554 " {new_statement}"
555 ).format(op=statement.bad_token, new_statement=new_statement)
556 if statement.bad_token != ",":
557 cause = no_op + cause
558 return {"cause": cause, "suggest": hint}
559
560 # def test(a, **, b): -> def test(a, c, b):
561 if statement.prev_token.string in ("(", ","):
562 # prevent getting an error because of repeated argument
563 unique_name = utils.unique_variable_name()
564 new_statement = fixers.replace_token(
565 statement.statement_tokens, statement.bad_token, unique_name
566 )
567 hint = _("You cannot use `{op}` as an argument.\n").format(
568 op=statement.bad_token
569 )
570 if fixers.check_statement(new_statement):
571 cause = _(
572 "I suspect you made a typo and wrote `{op}` by mistake.\n"
573 "If you replace it by a unique variable name, the result\n"
574 "will contain no syntax error.\n"
575 ).format(op=statement.bad_token)
576
577 else:
578 cause = (
579 _(
580 "I suspect you made a typo and wrote `{op}` by mistake,\n"
581 "perhaps instead of writing an identifier (variable name).\n"
582 )
583 + more_errors()
584 )
585 return {"cause": cause, "suggest": hint}
586
587 if statement.prev_token == "**":
588 cause = _(
589 "The `**` operator needs to be followed by an identifier (variable name).\n"
590 )
591 return {"cause": cause}
592
593 return {} # pragma: no cover
594
595
596 @add_statement_analyzer
597 def arg_after_kwarg(statement):
598 """This is only for something with positional argument after **kwargs;
599 the case where we have a positional argument after a named argument,
600 (..., a=1, b, ...) gets a specific error message.
601 """
602 if not (
603 statement.bad_token.is_identifier()
604 and statement.prev_token == ","
605 and statement.next_token in (",", ")")
606 ):
607 return {}
608
609 for tok in statement.tokens[ASYNC : statement.bad_token_index]:
610 if tok == "**":
611 hint = _("Positional arguments must come before keyword arguments.\n")
612 cause = hint + _(
613 "`{arg}` is a positional argument that appears after one or more\n"
614 "keyword arguments in your function definition.\n"
615 ).format(arg=statement.bad_token.string)
616 return {"cause": cause, "suggest": hint}
617
618 return {}