Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 28179aa

Browse files
bpo-42918: Improve build-in function compile() in mode 'single' (GH-29934)
Co-authored-by: Alex Waygood <[email protected]>
1 parent 98e506a commit 28179aa

3 files changed

Lines changed: 6 additions & 19 deletions

File tree

Lib/test/test_compile.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -504,6 +504,7 @@ def test_single_statement(self):
504504
self.compile_single("if x:\n f(x)")
505505
self.compile_single("if x:\n f(x)\nelse:\n g(x)")
506506
self.compile_single("class T:\n pass")
507+
self.compile_single("c = '''\na=1\nb=2\nc=3\n'''")
507508

508509
def test_bad_single_statement(self):
509510
self.assertInvalidSingle('1\n2')
@@ -514,6 +515,7 @@ def test_bad_single_statement(self):
514515
self.assertInvalidSingle('f()\n# blah\nblah()')
515516
self.assertInvalidSingle('f()\nxy # blah\nblah()')
516517
self.assertInvalidSingle('x = 5 # comment\nx = 6\n')
518+
self.assertInvalidSingle("c = '''\nd=1\n'''\na = 1\n\nb = 2\n")
517519

518520
def test_particularly_evil_undecodable(self):
519521
# Issue 24022
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix bug where the built-in :func:`compile` function did not always raise a
2+
:exc:`SyntaxError` when passed multiple statements in 'single' mode. Patch by
3+
Weipeng Hong.

Parser/pegen.c

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -675,31 +675,13 @@ _PyPegen_number_token(Parser *p)
675675
t->end_col_offset, p->arena);
676676
}
677677

678-
static int // bool
679-
newline_in_string(Parser *p, const char *cur)
680-
{
681-
for (const char *c = cur; c >= p->tok->buf; c--) {
682-
if (*c == '\'' || *c == '"') {
683-
return 1;
684-
}
685-
}
686-
return 0;
687-
}
688-
689678
/* Check that the source for a single input statement really is a single
690679
statement by looking at what is left in the buffer after parsing.
691680
Trailing whitespace and comments are OK. */
692681
static int // bool
693682
bad_single_statement(Parser *p)
694683
{
695-
const char *cur = strchr(p->tok->buf, '\n');
696-
697-
/* Newlines are allowed if preceded by a line continuation character
698-
or if they appear inside a string. */
699-
if (!cur || (cur != p->tok->buf && *(cur - 1) == '\\')
700-
|| newline_in_string(p, cur)) {
701-
return 0;
702-
}
684+
char *cur = p->tok->cur;
703685
char c = *cur;
704686

705687
for (;;) {

0 commit comments

Comments
 (0)