Skip to content

Commit

Permalink
Rename exceptions to PyException etc; reintroduce deprecated ones
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Jul 11, 2020
1 parent a06aad5 commit 09f3a03
Show file tree
Hide file tree
Showing 30 changed files with 337 additions and 194 deletions.
14 changes: 8 additions & 6 deletions src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,12 @@ pub unsafe trait Element: Copy {
fn validate(b: &ffi::Py_buffer) -> PyResult<()> {
// shape and stride information must be provided when we use PyBUF_FULL_RO
if b.shape.is_null() {
return Err(exceptions::BufferError::py_err("Shape is Null"));
return Err(exceptions::PyBufferError::py_err("Shape is Null"));
}
if b.strides.is_null() {
return Err(exceptions::BufferError::py_err("PyBuffer: Strides is Null"));
return Err(exceptions::PyBufferError::py_err(
"PyBuffer: Strides is Null",
));
}
Ok(())
}
Expand Down Expand Up @@ -188,7 +190,7 @@ impl<T: Element> PyBuffer<T> {
{
Ok(buf)
} else {
Err(exceptions::BufferError::py_err(
Err(exceptions::PyBufferError::py_err(
"Incompatible type as buffer",
))
}
Expand Down Expand Up @@ -439,7 +441,7 @@ impl<T: Element> PyBuffer<T> {

fn copy_to_slice_impl(&self, py: Python, target: &mut [T], fort: u8) -> PyResult<()> {
if mem::size_of_val(target) != self.len_bytes() {
return Err(exceptions::BufferError::py_err(
return Err(exceptions::PyBufferError::py_err(
"Slice length does not match buffer length.",
));
}
Expand Down Expand Up @@ -526,7 +528,7 @@ impl<T: Element> PyBuffer<T> {
return buffer_readonly_error();
}
if mem::size_of_val(source) != self.len_bytes() {
return Err(exceptions::BufferError::py_err(
return Err(exceptions::PyBufferError::py_err(
"Slice length does not match buffer length.",
));
}
Expand Down Expand Up @@ -562,7 +564,7 @@ impl<T: Element> PyBuffer<T> {

#[inline(always)]
fn buffer_readonly_error() -> PyResult<()> {
Err(exceptions::BufferError::py_err(
Err(exceptions::PyBufferError::py_err(
"Cannot write to read-only buffer.",
))
}
Expand Down
4 changes: 2 additions & 2 deletions src/callback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//! Utilities for a Python callable object that invokes a Rust function.

use crate::err::PyResult;
use crate::exceptions::OverflowError;
use crate::exceptions::PyOverflowError;
use crate::ffi::{self, Py_hash_t};
use crate::IntoPyPointer;
use crate::{IntoPy, PyObject, Python};
Expand Down Expand Up @@ -85,7 +85,7 @@ impl IntoPyCallbackOutput<ffi::Py_ssize_t> for usize {
if self <= (isize::MAX as usize) {
Ok(self as isize)
} else {
Err(OverflowError::py_err(()))
Err(PyOverflowError::py_err(()))
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/class/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ where
ffi::Py_NE => Ok(CompareOp::Ne),
ffi::Py_GT => Ok(CompareOp::Gt),
ffi::Py_GE => Ok(CompareOp::Ge),
_ => Err(PyErr::new::<exceptions::ValueError, _>(
_ => Err(PyErr::new::<exceptions::PyValueError, _>(
"tp_richcompare called with invalid comparison operator",
)),
}
Expand Down
2 changes: 1 addition & 1 deletion src/class/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ impl IntoPyCallbackOutput<*mut ffi::PyObject> for PyIterNextOutput {
fn convert(self, _py: Python) -> PyResult<*mut ffi::PyObject> {
match self {
IterNextOutput::Yield(o) => Ok(o.into_ptr()),
IterNextOutput::Return(opt) => Err(crate::exceptions::StopIteration::py_err((opt,))),
IterNextOutput::Return(opt) => Err(crate::exceptions::PyStopIteration::py_err((opt,))),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/class/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ macro_rules! py_func_set {
let slf = py.from_borrowed_ptr::<$crate::PyCell<$generic>>(slf);

if value.is_null() {
Err($crate::PyErr::new::<exceptions::NotImplementedError, _>(
Err($crate::PyErr::new::<exceptions::PyNotImplementedError, _>(
format!(
"Subscript deletion not supported by {:?}",
stringify!($generic)
Expand Down Expand Up @@ -338,7 +338,7 @@ macro_rules! py_func_del {
.extract()?;
slf.try_borrow_mut()?.$fn_del(name).convert(py)
} else {
Err(PyErr::new::<exceptions::NotImplementedError, _>(
Err(PyErr::new::<exceptions::PyNotImplementedError, _>(
"Subscript assignment not supported",
))
}
Expand Down
2 changes: 1 addition & 1 deletion src/class/pyasync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ impl IntoPyCallbackOutput<*mut ffi::PyObject> for PyIterANextOutput {
match self {
IterANextOutput::Yield(o) => Ok(o.into_ptr()),
IterANextOutput::Return(opt) => {
Err(crate::exceptions::StopAsyncIteration::py_err((opt,)))
Err(crate::exceptions::PyStopAsyncIteration::py_err((opt,)))
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/class/sequence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,7 @@ mod sq_ass_item_impl {
let slf = py.from_borrowed_ptr::<PyCell<T>>(slf);

if value.is_null() {
return Err(PyErr::new::<exceptions::NotImplementedError, _>(format!(
return Err(PyErr::new::<exceptions::PyNotImplementedError, _>(format!(
"Item deletion is not supported by {:?}",
stringify!(T)
)));
Expand Down Expand Up @@ -256,7 +256,7 @@ mod sq_ass_item_impl {
if value.is_null() {
crate::callback::convert(py, slf.borrow_mut().__delitem__(key.into()))
} else {
Err(PyErr::new::<exceptions::NotImplementedError, _>(format!(
Err(PyErr::new::<exceptions::PyNotImplementedError, _>(format!(
"Item assignment not supported by {:?}",
stringify!(T)
)))
Expand Down
4 changes: 2 additions & 2 deletions src/derive_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
//! Functionality for the code generated by the derive backend

use crate::err::{PyErr, PyResult};
use crate::exceptions::TypeError;
use crate::exceptions::PyTypeError;
use crate::instance::PyNativeType;
use crate::pyclass::{PyClass, PyClassThreadChecker};
use crate::types::{PyAny, PyDict, PyModule, PyTuple};
Expand Down Expand Up @@ -43,7 +43,7 @@ pub fn parse_fn_args<'p>(
let nargs = args.len();
let mut used_args = 0;
macro_rules! raise_error {
($s: expr $(,$arg:expr)*) => (return Err(TypeError::py_err(format!(
($s: expr $(,$arg:expr)*) => (return Err(PyTypeError::py_err(format!(
concat!("{} ", $s), fname.unwrap_or("function") $(,$arg)*
))))
}
Expand Down
74 changes: 41 additions & 33 deletions src/err.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,14 @@ impl PyErr {
///
/// Example:
/// ```ignore
/// return Err(PyErr::new::<exceptions::TypeError, _>("Error message"));
/// return Err(PyErr::new::<exceptions::PyTypeError, _>("Error message"));
/// ```
///
/// In most cases, you can use a concrete exception's constructors instead:
/// the example is equivalent to
/// ```ignore
/// return Err(exceptions::TypeError::py_err("Error message"));
/// return exceptions::TypeError::into("Error message");
/// return Err(exceptions::PyTypeError::py_err("Error message"));
/// return exceptions::PyTypeError::into("Error message");
/// ```
pub fn new<T, V>(value: V) -> PyErr
where
Expand All @@ -105,7 +105,7 @@ impl PyErr {
/// Constructs a new error, with the usual lazy initialization of Python exceptions.
///
/// `exc` is the exception type; usually one of the standard exceptions
/// like `exceptions::RuntimeError`.
/// like `exceptions::PyRuntimeError`.
/// `args` is the a tuple of arguments to pass to the exception constructor.
pub fn from_type<A>(exc: &PyType, args: A) -> PyErr
where
Expand Down Expand Up @@ -161,7 +161,7 @@ impl PyErr {
}
} else {
PyErr {
ptype: exceptions::TypeError::type_object(obj.py()).into(),
ptype: exceptions::PyTypeError::type_object(obj.py()).into(),
pvalue: PyErrValue::ToObject(Box::new("exceptions must derive from BaseException")),
ptraceback: None,
}
Expand Down Expand Up @@ -257,7 +257,7 @@ impl PyErr {
};

let ptype = if ptype.is_null() {
<exceptions::SystemError as PyTypeObject>::type_object(py).into()
<exceptions::PySystemError as PyTypeObject>::type_object(py).into()
} else {
Py::from_owned_ptr(py, ptype)
};
Expand Down Expand Up @@ -344,7 +344,7 @@ impl PyErr {
///
/// This method takes `mut self` because the error might need
/// to be normalized in order to create the exception instance.
pub fn instance(mut self, py: Python) -> &exceptions::BaseException {
pub fn instance(mut self, py: Python) -> &exceptions::PyBaseException {
self.normalize(py);
match self.pvalue {
PyErrValue::Value(ref instance) => {
Expand Down Expand Up @@ -439,7 +439,7 @@ impl FromPy<PyErr> for PyObject {
}
}

impl FromPy<PyErr> for Py<exceptions::BaseException> {
impl FromPy<PyErr> for Py<exceptions::PyBaseException> {
fn from_py(other: PyErr, py: Python) -> Self {
other.instance(py).into()
}
Expand All @@ -462,7 +462,7 @@ impl<'a> IntoPy<PyObject> for &'a PyErr {
/// Convert `PyDowncastError` to Python `TypeError`.
impl std::convert::From<PyDowncastError> for PyErr {
fn from(_err: PyDowncastError) -> PyErr {
exceptions::TypeError::py_err(())
exceptions::PyTypeError::py_err(())
}
}

Expand Down Expand Up @@ -515,28 +515,30 @@ impl std::convert::From<io::Error> for PyErr {
}
match err.kind() {
io::ErrorKind::BrokenPipe => {
PyErr::from_value::<exceptions::BrokenPipeError>(err_value!())
PyErr::from_value::<exceptions::PyBrokenPipeError>(err_value!())
}
io::ErrorKind::ConnectionRefused => {
PyErr::from_value::<exceptions::ConnectionRefusedError>(err_value!())
PyErr::from_value::<exceptions::PyConnectionRefusedError>(err_value!())
}
io::ErrorKind::ConnectionAborted => {
PyErr::from_value::<exceptions::ConnectionAbortedError>(err_value!())
PyErr::from_value::<exceptions::PyConnectionAbortedError>(err_value!())
}
io::ErrorKind::ConnectionReset => {
PyErr::from_value::<exceptions::ConnectionResetError>(err_value!())
PyErr::from_value::<exceptions::PyConnectionResetError>(err_value!())
}
io::ErrorKind::Interrupted => {
PyErr::from_value::<exceptions::InterruptedError>(err_value!())
PyErr::from_value::<exceptions::PyInterruptedError>(err_value!())
}
io::ErrorKind::NotFound => {
PyErr::from_value::<exceptions::FileNotFoundError>(err_value!())
PyErr::from_value::<exceptions::PyFileNotFoundError>(err_value!())
}
io::ErrorKind::WouldBlock => {
PyErr::from_value::<exceptions::BlockingIOError>(err_value!())
PyErr::from_value::<exceptions::PyBlockingIOError>(err_value!())
}
io::ErrorKind::TimedOut => PyErr::from_value::<exceptions::TimeoutError>(err_value!()),
_ => PyErr::from_value::<exceptions::OSError>(err_value!()),
io::ErrorKind::TimedOut => {
PyErr::from_value::<exceptions::PyTimeoutError>(err_value!())
}
_ => PyErr::from_value::<exceptions::PyOSError>(err_value!()),
}
}
}
Expand All @@ -549,7 +551,7 @@ impl PyErrArguments for io::Error {

impl<W: 'static + Send + std::fmt::Debug> std::convert::From<std::io::IntoInnerError<W>> for PyErr {
fn from(err: std::io::IntoInnerError<W>) -> PyErr {
PyErr::from_value::<exceptions::OSError>(PyErrValue::from_err_args(err))
PyErr::from_value::<exceptions::PyOSError>(PyErrValue::from_err_args(err))
}
}

Expand All @@ -567,22 +569,28 @@ impl PyErrArguments for std::convert::Infallible {

impl std::convert::From<std::convert::Infallible> for PyErr {
fn from(_: std::convert::Infallible) -> PyErr {
PyErr::new::<exceptions::ValueError, _>("Infalliable!")
PyErr::new::<exceptions::PyValueError, _>("Infalliable!")
}
}

impl_to_pyerr!(std::array::TryFromSliceError, exceptions::ValueError);
impl_to_pyerr!(std::num::ParseIntError, exceptions::ValueError);
impl_to_pyerr!(std::num::ParseFloatError, exceptions::ValueError);
impl_to_pyerr!(std::num::TryFromIntError, exceptions::ValueError);
impl_to_pyerr!(std::str::ParseBoolError, exceptions::ValueError);
impl_to_pyerr!(std::ffi::IntoStringError, exceptions::UnicodeDecodeError);
impl_to_pyerr!(std::ffi::NulError, exceptions::ValueError);
impl_to_pyerr!(std::str::Utf8Error, exceptions::UnicodeDecodeError);
impl_to_pyerr!(std::string::FromUtf8Error, exceptions::UnicodeDecodeError);
impl_to_pyerr!(std::string::FromUtf16Error, exceptions::UnicodeDecodeError);
impl_to_pyerr!(std::char::DecodeUtf16Error, exceptions::UnicodeDecodeError);
impl_to_pyerr!(std::net::AddrParseError, exceptions::ValueError);
impl_to_pyerr!(std::array::TryFromSliceError, exceptions::PyValueError);
impl_to_pyerr!(std::num::ParseIntError, exceptions::PyValueError);
impl_to_pyerr!(std::num::ParseFloatError, exceptions::PyValueError);
impl_to_pyerr!(std::num::TryFromIntError, exceptions::PyValueError);
impl_to_pyerr!(std::str::ParseBoolError, exceptions::PyValueError);
impl_to_pyerr!(std::ffi::IntoStringError, exceptions::PyUnicodeDecodeError);
impl_to_pyerr!(std::ffi::NulError, exceptions::PyValueError);
impl_to_pyerr!(std::str::Utf8Error, exceptions::PyUnicodeDecodeError);
impl_to_pyerr!(std::string::FromUtf8Error, exceptions::PyUnicodeDecodeError);
impl_to_pyerr!(
std::string::FromUtf16Error,
exceptions::PyUnicodeDecodeError
);
impl_to_pyerr!(
std::char::DecodeUtf16Error,
exceptions::PyUnicodeDecodeError
);
impl_to_pyerr!(std::net::AddrParseError, exceptions::PyValueError);

pub fn panic_after_error(_py: Python) -> ! {
unsafe {
Expand Down Expand Up @@ -611,7 +619,7 @@ mod tests {
fn set_typeerror() {
let gil = Python::acquire_gil();
let py = gil.python();
let err: PyErr = exceptions::TypeError::py_err(());
let err: PyErr = exceptions::PyTypeError::py_err(());
err.restore(py);
assert!(PyErr::occurred(py));
drop(PyErr::fetch(py));
Expand Down
Loading

0 comments on commit 09f3a03

Please sign in to comment.