Skip to content

Commit

Permalink
pythongh-109118: Fix runtime crash when NameError happens in PEP 695 …
Browse files Browse the repository at this point in the history
…function
  • Loading branch information
JelleZijlstra committed Sep 8, 2023
1 parent b9831e5 commit 3c448e8
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 8 deletions.
40 changes: 40 additions & 0 deletions Lib/test/test_type_params.py
Expand Up @@ -956,3 +956,43 @@ class NewStyle[T]:
for case in cases:
with self.subTest(case=case):
weakref.ref(case)


class TypeParamsRuntimeTest(unittest.TestCase):
def test_name_error(self):
# gh-109118: This crashed the interpreter due to a refcounting bug
code = """
class name_2[name_5]:
class name_4[name_5](name_0):
pass
"""
with self.assertRaises(NameError):
run_code(code)

# Crashed with a slightly different stack trace
code = """
class name_2[name_5]:
class name_4[name_5: name_5](name_0):
pass
"""
with self.assertRaises(NameError):
run_code(code)

def test_broken_class_namespace(self):
code = """
class WeirdMapping(dict):
def __missing__(self, key):
if key == "T":
raise RuntimeError
raise KeyError(key)
class Meta(type):
def __prepare__(name, bases):
return WeirdMapping()
class MyClass[V](metaclass=Meta):
class Inner[U](T):
pass
"""
with self.assertRaises(RuntimeError):
run_code(code)
@@ -0,0 +1,2 @@
Fix interpreter crash when a NameError is raised inside the type parameters
of a generic class.
3 changes: 1 addition & 2 deletions Python/bytecodes.c
Expand Up @@ -1301,10 +1301,8 @@ dummy_func(
op(_LOAD_FROM_DICT_OR_GLOBALS, (mod_or_class_dict -- v)) {
PyObject *name = GETITEM(FRAME_CO_NAMES, oparg);
if (PyMapping_GetOptionalItem(mod_or_class_dict, name, &v) < 0) {
Py_DECREF(mod_or_class_dict);
goto error;
}
Py_DECREF(mod_or_class_dict);
if (v == NULL) {
v = PyDict_GetItemWithError(GLOBALS(), name);
if (v != NULL) {
Expand All @@ -1325,6 +1323,7 @@ dummy_func(
}
}
}
Py_DECREF(mod_or_class_dict);
}

macro(LOAD_NAME) = _LOAD_LOCALS + _LOAD_FROM_DICT_OR_GLOBALS;
Expand Down
3 changes: 1 addition & 2 deletions Python/executor_cases.c.h

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

6 changes: 2 additions & 4 deletions Python/generated_cases.c.h

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

0 comments on commit 3c448e8

Please sign in to comment.