Skip to content

gh-137376: ensure that SyntaxError are properly detected in REPL #137378

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

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions Include/internal/pycore_global_objects_fini_generated.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Include/internal/pycore_global_strings.h
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,7 @@ struct _Py_global_strings {
STRUCT_FOR_ID(fd)
STRUCT_FOR_ID(fd2)
STRUCT_FOR_ID(fdel)
STRUCT_FOR_ID(feature_version)
STRUCT_FOR_ID(fget)
STRUCT_FOR_ID(fields)
STRUCT_FOR_ID(file)
Expand Down
1 change: 1 addition & 0 deletions Include/internal/pycore_runtime_init_generated.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions Include/internal/pycore_unicodeobject_generated.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 20 additions & 0 deletions Lib/_pyrepl/console.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,12 @@
from __future__ import annotations

import _colorize
import _symtable # type: ignore[import-not-found]

from abc import ABC, abstractmethod
import ast
import code
import codeop
import linecache
from dataclasses import dataclass, field
import os.path
Expand Down Expand Up @@ -211,6 +213,24 @@ def runsource(self, source, filename="<input>", symbol="single"):
except (OverflowError, ValueError):
self.showsyntaxerror(filename, source=source)
return False

# Validate stuff that cannot be validated with AST parsing only,
# such as assigning to a variable before a global declaration,
#
# While runsource("x = 1; global x") would fail, runsource("x = 1")
# followed by runsource("global x") would still work since preventing
# this requires the REPL to remember the global names whose number
# grows faster than in a regular program, which then becomes less
# efficient or relevant for the user.
flags = self.compile.compiler.flags # may contain active futures
flags &= ~codeop.PyCF_DONT_IMPLY_DEDENT
flags &= ~codeop.PyCF_ALLOW_INCOMPLETE_INPUT
try:
_symtable.symtable(source, filename, "exec", flags=flags)
except (SyntaxError, OverflowError, ValueError):
self.showsyntaxerror(filename, source=source)
return False

if tree.body:
*_, last_stmt = tree.body
for stmt in tree.body:
Expand Down
61 changes: 43 additions & 18 deletions Lib/test/test_pyrepl/test_interact.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from unittest.mock import patch
from textwrap import dedent

from test.support import force_not_colorized
from test.support import captured_stdout, force_not_colorized

from _pyrepl.console import InteractiveColoredConsole
from _pyrepl.simple_interact import _more_lines
Expand Down Expand Up @@ -131,6 +131,11 @@ def test_runsource_shows_syntax_error_for_failed_compilation(self):
console.runsource(source)
mock_showsyntaxerror.assert_called_once()

def test_runsource_shows_syntax_error_for_failed_symtable_checks(self):
# Some checks cannot be performed by AST parsing only.
# See https://github.com/python/cpython/issues/137376.
self._test_runsource_error("x = 1; global x; x = 2")

def test_runsource_survives_null_bytes(self):
console = InteractiveColoredConsole()
source = "\x00\n"
Expand All @@ -153,26 +158,46 @@ def test_no_active_future(self):
self.assertEqual(f.getvalue(), "{'x': <class 'int'>}\n")

def test_future_annotations(self):
console = InteractiveColoredConsole()
source = dedent("""\
from __future__ import annotations
def g(x: int): ...
print(g.__annotations__)
""")
f = io.StringIO()
with contextlib.redirect_stdout(f):
result = console.runsource(source)
self.assertFalse(result)
self.assertEqual(f.getvalue(), "{'x': 'int'}\n")
self._test_runsource_future(
"from __future__ import annotations",
["def g(x: int): ...", "print(g.__annotations__)"],
"{'x': 'int'}\n",
)

def test_future_barry_as_flufl(self):
self._test_runsource_future(
"from __future__ import barry_as_FLUFL",
["""print("black" <> 'blue')"""],
"True\n",
)

def _test_runsource_error(self, buggy_source):
console = InteractiveColoredConsole()
f = io.StringIO()
with contextlib.redirect_stdout(f):
result = console.runsource("from __future__ import barry_as_FLUFL\n")
result = console.runsource("""print("black" <> 'blue')\n""")
self.assertFalse(result)
self.assertEqual(f.getvalue(), "True\n")
with patch.object(console, "showsyntaxerror") as handler:
result = console.runsource(buggy_source)
handler.assert_called_once()

def _test_runsource_future(self, future_statement, statements, expected):
"""Run future_statement + statements.

This checks whether a standalone future statement remains active
for the entire session lifetime.
"""
with self.subTest("standalone source"):
console = InteractiveColoredConsole()
source = "\n".join([future_statement, *statements])
with captured_stdout() as stdout:
result = console.runsource(source)
self.assertFalse(result)
self.assertEqual(stdout.getvalue(), expected)

with self.subTest("__future__ executed separtely"):
console = InteractiveColoredConsole()
with captured_stdout() as stdout:
result = console.runsource(future_statement)
result = console.runsource("\n".join(statements))
self.assertFalse(result)
self.assertEqual(stdout.getvalue(), expected)


class TestMoreLines(unittest.TestCase):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Ensure that :exc:`SyntaxError` is raised when given incorrect REPL inputs
that are only detected when processing symbol tables. Patch by Bénédikt
Tran.
72 changes: 64 additions & 8 deletions Modules/clinic/symtablemodule.c.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 14 additions & 3 deletions Modules/symtablemodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,33 @@ _symtable.symtable
filename: object(converter='PyUnicode_FSDecoder')
startstr: str
/
*
flags: int = 0
feature_version: int = -1

Return symbol and scope dictionaries used internally by compiler.
[clinic start generated code]*/

static PyObject *
_symtable_symtable_impl(PyObject *module, PyObject *source,
PyObject *filename, const char *startstr)
/*[clinic end generated code: output=59eb0d5fc7285ac4 input=9dd8a50c0c36a4d7]*/
PyObject *filename, const char *startstr, int flags,
int feature_version)
/*[clinic end generated code: output=1e766ac3387e156a input=03e9deda7ab5a9d7]*/
{
struct symtable *st;
PyObject *t;
int start;
PyCompilerFlags cf = _PyCompilerFlags_INIT;
PyObject *source_copy = NULL;

cf.cf_flags = PyCF_SOURCE_IS_UTF8;
cf.cf_flags = flags | PyCF_SOURCE_IS_UTF8;
if (feature_version >= 0 && (flags & PyCF_ONLY_AST)) {
cf.cf_feature_version = feature_version;
}
if (flags & ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_COMPILE_MASK)) {
PyErr_SetString(PyExc_ValueError, "_symtable.symtable(): unrecognised flags");
return NULL;
}

const char *str = _Py_SourceAsString(source, "symtable", "string or bytes", &cf, &source_copy);
if (str == NULL) {
Expand Down
Loading