Skip to content

bpo-45848: Delimitate when source lines can't be located in the parser error handling functions #29626

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

Closed
wants to merge 2 commits into from
Closed
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
36 changes: 35 additions & 1 deletion Lib/test/test_peg_generator/test_c_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from test import test_tools
from test import support
from test.support import os_helper
from test.support.script_helper import assert_python_ok
from test.support.script_helper import assert_python_ok, run_python_until_end

_py_cflags_nodist = sysconfig.get_config_var("PY_CFLAGS_NODIST")
_pgo_flag = sysconfig.get_config_var("PGO_PROF_USE_FLAG")
Expand Down Expand Up @@ -483,3 +483,37 @@ def test_forced_with_group(self) -> None:
self.assertIn("expected (':' | ';')", e.exception.args[0])
"""
self.run_test(grammar_source, test_source)


class TestCPythonParserEdgeCases(unittest.TestCase):
def setUp(self):
self.tmp_path = tempfile.mkdtemp()
change_cwd = os_helper.change_cwd(self.tmp_path)
change_cwd.__enter__()
self.addCleanup(change_cwd.__exit__, None, None, None)
self.addCleanup(shutil.rmtree, self.tmp_path)

def assert_python(
self, test_source, expected="", not_expected="", encoding="utf8"
):
test_source = textwrap.dedent(test_source)
with tempfile.NamedTemporaryFile(dir=self.tmp_path, suffix=".py") as f:
f.write(test_source.encode(encoding))
f.flush()
result, _cmdline = run_python_until_end(f.name)
_rc, out_b, err_b = result
output = out_b.decode() + "\n" + err_b.decode()
if not_expected:
self.assertNotIn(not_expected, output)
if expected:
self.assertIn(expected, output)

def test_encoding_cookie(self):
self.assert_python(
"""
# encoding: ascii
(
""",
expected="'(' was never closed",
not_expected="Fatal Python error: Aborted",
)
5 changes: 4 additions & 1 deletion Parser/pegen.c
Original file line number Diff line number Diff line change
Expand Up @@ -504,9 +504,12 @@ _PyPegen_raise_error_known_location(Parser *p, PyObject *errtype,
Py_ssize_t size = p->tok->inp - p->tok->buf;
error_line = PyUnicode_DecodeUTF8(p->tok->buf, size, "replace");
}
else {
else if (p->tok->fp == NULL || p->tok->fp == stdin) {
error_line = get_error_line(p, lineno);
}
else {
error_line = PyUnicode_FromStringAndSize("", 0);
}
if (!error_line) {
goto error;
}
Expand Down