Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bpo-45759: Better error messages for non-matching 'elif'/'else' statements #29513

Merged
merged 16 commits into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
4fa7e84
bpo-45759: Better error messages for non-matching 'elif'/'else' state…
thatbirdguythatuknownot Nov 10, 2021
28bef91
bpo-45759: Better error messages for non-matching 'elif'/'else' state…
thatbirdguythatuknownot Nov 10, 2021
22b201d
bpo-45759: Better error messages for non-matching 'elif'/'else' state…
thatbirdguythatuknownot Nov 10, 2021
1f86e84
bpo-45759: Better error messages for non-matching 'elif'/'else' state…
thatbirdguythatuknownot Nov 10, 2021
58911bc
📜🤖 Added by blurb_it.
blurb-it[bot] Nov 10, 2021
f34642b
bpo-45759: Better error messages for non-matching 'elif'/'else' state…
thatbirdguythatuknownot Nov 10, 2021
40a17ad
bpo-45759: Better error messages for non-matching 'elif'/'else' state…
thatbirdguythatuknownot Nov 10, 2021
c33b64b
bpo-45759: Better error messages for non-matching 'elif'/'else' state…
thatbirdguythatuknownot Nov 10, 2021
a3389e8
bpo-45759: Better error messages for non-matching 'elif'/'else' state…
thatbirdguythatuknownot Nov 10, 2021
0a33eb2
bpo-45759: Better error messages for non-matching 'elif'/'else' state…
thatbirdguythatuknownot Nov 10, 2021
beca365
bpo-45759: Better error messages for non-matching 'elif'/'else' state…
thatbirdguythatuknownot Nov 10, 2021
0acd364
bpo-45759: Better error messages for non-matching 'elif'/'else' state…
thatbirdguythatuknownot Nov 25, 2021
40c7abd
Merge branch 'main' into patch-4
lysnikolaou Sep 14, 2023
b3d3c08
Fix test_syntax
lysnikolaou Sep 14, 2023
e9b8aad
Merge remote-tracking branch 'upstream/main' into patch-4
pablogsal Oct 31, 2023
a0cc84a
fixup! Merge remote-tracking branch 'upstream/main' into patch-4
pablogsal Oct 31, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Grammar/python.gram
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ simple_stmt[stmt_ty] (memo):
| &'nonlocal' nonlocal_stmt

compound_stmt[stmt_ty]:
| invalid_compound_stmt
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is more acceptable, but it will trigger with any compound statement:

with A():
    elif 3:
        ...
SyntaxError: 'elif' must match an if-statement here

Also, a slight minor problem is that at this level we are catching an incorrect keyword in a specific bad context, but there could be lot more. For instance, if you would write:

[x for x in range(3) if 34 elif 12]

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there anything I should do about those?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No for now, let's discuss first if we are ok with this. We may need to adapt the error message

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No for now, let's discuss first if we are ok with this.

I mean, let's wait to see what @lysnikolaou and @isidentical think

Copy link
Member

@pablogsal pablogsal Nov 10, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe also @cfbolz if he has some time

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pablogsal should we keep waiting for the other reviewers, or should this pull request be closed?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pablogsal should we keep waiting for the other reviewers, or should this pull request be closed?

We should wait for other reviewers.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am currently unable to comment on this issue, so feel free to skip me.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pablogsal It's been 7 days and I plan on closing this pull request because of inactivity. Should we keep waiting for @lysnikolaou?

| &('def' | '@' | ASYNC) function_def
| &'if' if_stmt
| &('class' | '@') class_def
Expand Down Expand Up @@ -1174,6 +1175,10 @@ invalid_import_from_targets:
| import_from_as_names ',' NEWLINE {
RAISE_SYNTAX_ERROR("trailing comma not allowed without surrounding parentheses") }

invalid_compound_stmt:
| a='elif' named_expression ':' { RAISE_SYNTAX_ERROR_STARTING_FROM(a, "'elif' must match an if-statement here") }
| a='else' ':' { RAISE_SYNTAX_ERROR_STARTING_FROM(a, "'else' must match a valid statement here") }

invalid_with_stmt:
| [ASYNC] 'with' ','.(expression ['as' star_target])+ &&':'
| [ASYNC] 'with' '(' ','.(expressions ['as' star_target])+ ','? ')' &&':'
Expand Down
61 changes: 59 additions & 2 deletions Lib/test/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -1280,6 +1280,28 @@
... ...
Traceback (most recent call last):
SyntaxError: positional patterns follow keyword patterns

Non-matching 'elif'/'else' statements:

>>> if a == b:
... ...
... elif a == c:
Traceback (most recent call last):
SyntaxError: 'elif' must match an if-statement here

>>> if x == y:
... ...
... else:
Traceback (most recent call last):
SyntaxError: 'else' must match a valid statement here

>>> elif m == n:
Traceback (most recent call last):
SyntaxError: 'elif' must match an if-statement here

>>> else:
Traceback (most recent call last):
SyntaxError: 'else' must match a valid statement here
"""

import re
Expand All @@ -1295,8 +1317,8 @@ def _check_error(self, code, errtext,
lineno=None, offset=None, end_lineno=None, end_offset=None):
"""Check that compiling code raises SyntaxError with errtext.

errtest is a regular expression that must be present in the
test of the exception raised. If subclass is specified it
errtext is a regular expression that must be present in the
test of the exception raised. If subclass is specified, it
is the expected subclass of SyntaxError (e.g. IndentationError).
"""
try:
Expand All @@ -1320,6 +1342,22 @@ def _check_error(self, code, errtext,
else:
self.fail("compile() did not raise SyntaxError")

def _check_noerror(self, code,
errtext="compile() raised unexpected SyntaxError",
filename="<testcase>", mode="exec", subclass=None):
"""Check that compiling code does not raise a SyntaxError.

errtext is the message passed to self.fail if there is
a SyntaxError. If the subclass parameter is specified,
it is the subclass of SyntaxError (e.g. IndentationError)
that the raised error is checked against.
"""
try:
compile(code, filename, mode)
except SyntaxError as err:
if (not subclass) or isinstance(err, subclass):
self.fail(errtext)

def test_expression_with_assignment(self):
self._check_error(
"print(end1 + end2 = ' ')",
Expand Down Expand Up @@ -1582,6 +1620,25 @@ def test_syntax_error_on_deeply_nested_blocks(self):
"""
self._check_error(source, "too many statically nested blocks")

def test_syntax_error_non_matching_elif_else_statements(self):
# Check bpo-45759: 'elif' statements that doesn't match an
# if-statement or 'else' statements that doesn't match any
# valid else-able statement (e.g. 'while')
self._check_error(
"elif m == n:\n ...",
"'elif' must match an if-statement here")
self._check_error(
"else:\n ...",
"'else' must match a valid statement here")
self._check_noerror("if a == b:\n ...\nelif a == c:\n ...")
self._check_noerror("if x == y:\n ...\nelse:\n ...")
self._check_error(
"else = 123",
"invalid syntax")
self._check_error(
"elif 55 = 123",
"invalid syntax")


def load_tests(loader, tests, pattern):
tests.addTest(doctest.DocTestSuite())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved error messages for ``elif``/``else`` statements not matching any valid statements. Patch by Jeremiah Vivian.
Loading