Skip to content
Merged
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
8 changes: 8 additions & 0 deletions mypyc/irbuild/generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
from mypyc.irbuild.nonlocalcontrol import ExceptNonlocalControl, gen_generator_func_cleanup
from mypyc.irbuild.targets import AssignmentTargetAttr
from mypyc.primitives.exc_ops import (
check_throw_args_op,
error_catch_op,
exc_matches_op,
raise_exception_with_tb_op,
Expand Down Expand Up @@ -332,6 +333,13 @@ def add_throw_to_generator_class(builder: IRBuilder, fn_info: FuncInfo, fn_decl:
builder.assign_if_null(val, lambda: none_reg, fn_info.fitem.line)
builder.assign_if_null(tb, lambda: none_reg, fn_info.fitem.line)

# Reject invalid arguments before resuming the generator.
builder.call_c(
check_throw_args_op,
[builder.read(typ), builder.read(val), builder.read(tb)],
fn_info.fitem.line,
)

# Call the helper function using the arguments passed in, and return that result.
result = builder.add(
Call(
Expand Down
1 change: 1 addition & 0 deletions mypyc/lib-rt/CPy.h
Original file line number Diff line number Diff line change
Expand Up @@ -1140,6 +1140,7 @@ void CPy_Raise(PyObject *exc);
void CPy_RaiseFrom(PyObject *exc, PyObject *cause);
void CPy_Reraise(void);
void CPyErr_SetObjectAndTraceback(PyObject *type, PyObject *value, PyObject *traceback);
bool CPyGen_CheckThrowArgs(PyObject *type, PyObject *value, PyObject *traceback);
tuple_T3OOO CPy_CatchError(void);
void CPy_RestoreExcInfo(tuple_T3OOO info);
bool CPy_ExceptionMatches(PyObject *type);
Expand Down
30 changes: 30 additions & 0 deletions mypyc/lib-rt/exc_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,13 @@ void CPy_RaiseFrom(PyObject *exc, PyObject *cause) {
void CPy_Reraise(void) {
PyObject *p_type, *p_value, *p_traceback;
PyErr_GetExcInfo(&p_type, &p_value, &p_traceback);
if (p_value == NULL || Py_IsNone(p_value)) {
Py_XDECREF(p_type);
Py_XDECREF(p_value);
Py_XDECREF(p_traceback);
PyErr_SetString(PyExc_RuntimeError, "No active exception to reraise");
return;
}
PyErr_Restore(p_type, p_value, p_traceback);
}

Expand All @@ -96,6 +103,29 @@ void CPyErr_SetObjectAndTraceback(PyObject *type, PyObject *value, PyObject *tra
PyErr_Restore(type, value, traceback);
}

// Validate the arguments of generator.throw() before resuming the generator, like
// CPython's _gen_throw. Return false and set an error if they are invalid.
bool CPyGen_CheckThrowArgs(PyObject *type, PyObject *value, PyObject *traceback) {
if (!Py_IsNone(traceback) && !PyTraceBack_Check(traceback)) {
PyErr_SetString(PyExc_TypeError, "throw() third argument must be a traceback object");
return false;
}
if (PyExceptionClass_Check(type)) {
return true;
}
if (PyExceptionInstance_Check(type)) {
if (!Py_IsNone(value)) {
PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value");
return false;
}
return true;
}
PyErr_Format(PyExc_TypeError,
"exceptions must be classes or instances deriving from BaseException, not %s",
Py_TYPE(type)->tp_name);
return false;
}

tuple_T3OOO CPy_CatchError(void) {
// We need to return the existing sys.exc_info() information, so
// that it can be restored when we finish handling the error we
Expand Down
8 changes: 8 additions & 0 deletions mypyc/lib-rt/function_wrapper.c
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,14 @@ static PyObject* CPyFunction_Vectorcall(PyObject *func, PyObject *const *args, s

self = ((PyCFunctionObject *)f)->m_self;
if (!self) {
if (unlikely(nargs < 1)) {
PyObject *name = CPyFunction_get_name(func, NULL);
if (name != NULL) {
PyErr_Format(PyExc_TypeError, "unbound method %U() needs an argument", name);
Py_DECREF(name);
}
return NULL;
}
self = args[0];
args += 1;
nargs -= 1;
Expand Down
8 changes: 8 additions & 0 deletions mypyc/primitives/exc_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,14 @@
error_kind=ERR_ALWAYS,
)

# Check that the (type, value, traceback) arguments of generator.throw() are valid.
check_throw_args_op = custom_op(
arg_types=[object_rprimitive, object_rprimitive, object_rprimitive],
return_type=bit_rprimitive,
c_function_name="CPyGen_CheckThrowArgs",
error_kind=ERR_FALSE,
)

# Reraise the currently raised exception.
reraise_exception_op = custom_op(
arg_types=[], return_type=void_rtype, c_function_name="CPy_Reraise", error_kind=ERR_ALWAYS
Expand Down
45 changes: 45 additions & 0 deletions mypyc/test-data/run-async.test
Original file line number Diff line number Diff line change
Expand Up @@ -2957,3 +2957,48 @@ with assertRaises(MyError):
pyiter_send(fails(), None)

[typing fixtures/typing-full.pyi]

[case testCallUnboundAsyncMethodWithoutSelf]
class C:
async def m(self) -> int:
return 1

@classmethod
async def c(cls) -> str:
return cls.__name__

@staticmethod
async def s() -> int:
return 2

[file driver.py]
from typing import Any
from native import C
from testutil import assertRaises

def run(coro: Any) -> Any:
try:
coro.send(None)
except StopIteration as e:
return e.value
assert False

assert run(C().m()) == 1
assert run(C.m(C())) == 1
assert run(C.c()) == "C"
assert run(C().c()) == "C"
assert run(C.s()) == 2

# Calling the underlying function without self (or cls) used to read out of bounds.
with assertRaises(TypeError, "unbound method C.m() needs an argument"):
C.m()
with assertRaises(TypeError, "unbound method C.m() needs an argument"):
C.__dict__["m"]()
with assertRaises(TypeError, "unbound method C.m() needs an argument"):
C.__dict__["m"].__call__()
with assertRaises(TypeError, "unbound method C.c() needs an argument"):
C.__dict__["c"]()
with assertRaises(TypeError, "unbound method C.c() needs an argument"):
C.__dict__["c"].__call__()
assert run(C.__dict__["m"](C())) == 1
assert run(C.__dict__["c"](C)) == "C"
47 changes: 47 additions & 0 deletions mypyc/test-data/run-exceptions.test
Original file line number Diff line number Diff line change
Expand Up @@ -694,3 +694,50 @@ def gen() -> Iterator[str]:

def test_generator() -> None:
assert list(gen()) == ["KeyError('z')"]

[case testBareRaiseWithoutActiveException]
from testutil import assertRaises

def reraise() -> None:
raise

def reraise_caught() -> str:
try:
raise
except RuntimeError as e:
return str(e)

def test_no_active_exception() -> None:
with assertRaises(RuntimeError, "No active exception to reraise"):
reraise()
assert reraise_caught() == "No active exception to reraise"

def test_after_handled_exception() -> None:
try:
raise ValueError("x")
except ValueError:
pass
with assertRaises(RuntimeError, "No active exception to reraise"):
reraise()

def test_active_exception() -> None:
try:
raise ValueError("x")
except ValueError:
with assertRaises(ValueError, "x"):
reraise()

[file driver.py]
import sys
import native

native.test_no_active_exception()
native.test_after_handled_exception()
native.test_active_exception()
assert sys.exc_info() == (None, None, None)
try:
native.reraise()
except RuntimeError as e:
assert str(e) == "No active exception to reraise"
else:
assert False
81 changes: 81 additions & 0 deletions mypyc/test-data/run-generators.test
Original file line number Diff line number Diff line change
Expand Up @@ -1581,3 +1581,84 @@ g2 = gen_delegate(reenter())
box.append(g2)
assert pyiter_send(g2, None) == (PYGEN_NEXT, 2)
assert pyiter_send(g2, None) == (PYGEN_RETURN, None)

[case testGeneratorThrowInvalidArguments]
from typing import Any, Generator

from testutil import assertRaises

def gen() -> Generator[Any, None, None]:
while True:
try:
yield 1
except BaseException as e:
yield "caught " + type(e).__name__

async def coro() -> int:
return 1

def started() -> Any:
g = gen()
assert next(g) == 1
return g

def test_valid_arguments() -> None:
g = started()
assert g.throw(ValueError) == "caught ValueError"
assert next(g) == 1
assert g.throw(ValueError, "x") == "caught ValueError"
assert next(g) == 1
assert g.throw(ValueError("x"), None) == "caught ValueError"
assert next(g) == 1
try:
raise KeyError
except KeyError as e:
tb = getattr(e, "__traceback__")
assert g.throw(ValueError, ValueError("x"), tb) == "caught ValueError"
assert next(g) == 1
assert g.throw(ValueError("x"), None, None) == "caught ValueError"

# The errors must be raised by throw() without resuming the generator, so the except
# clause in gen() doesn't see them.

def test_invalid_traceback() -> None:
g = started()
with assertRaises(TypeError, "throw() third argument must be a traceback object"):
g.throw(ValueError, None, 42)
assert next(g) == 1

def test_instance_with_separate_value() -> None:
g = started()
with assertRaises(TypeError, "instance exception may not have a separate value"):
g.throw(ValueError("x"), 5)
assert next(g) == 1

def test_non_exception_class() -> None:
g = started()
with assertRaises(
TypeError, "exceptions must be classes or instances deriving from BaseException, not type"
):
g.throw(int)
assert next(g) == 1

def test_non_exception_instance() -> None:
g = started()
msg = "exceptions must be classes or instances deriving from BaseException, not "
with assertRaises(TypeError, msg + "int"):
g.throw(5)
with assertRaises(TypeError, msg + "object"):
g.throw(object())
assert next(g) == 1

# Not yet started
g2: Any = gen()
with assertRaises(TypeError, msg + "int"):
g2.throw(5)
assert next(g2) == 1

def test_coroutine() -> None:
c: Any = coro()
with assertRaises(TypeError, "exceptions must be classes or instances"):
c.throw(5)
with assertRaises(StopIteration):
c.send(None)
Loading