Skip to main content

rigetti_pyo3/
errors.rs

1//! Macros for Python exceptions from Rust errors with correct stub types.
2
3#[cfg(not(feature = "stubs"))]
4/// Create a new Python exception.
5#[macro_export]
6macro_rules! create_exception {
7    ( $module:expr, $py_err: ident, $base: ty ) => {
8        $crate::create_exception!($module, $py_err, $base, "");
9    };
10    ( $module:expr, $py_err: ident, $base: ty, $doc: expr ) => {
11        $crate::pyo3::create_exception!($module, $py_err, $base, $doc);
12    };
13}
14
15#[cfg(feature = "stubs")]
16/// Create a new Python exception using the correct macro
17/// based on whether a "stubs" features is active.
18#[macro_export]
19macro_rules! create_exception {
20    ( $module:expr, $py_err: ident, $base: ty ) => {
21        $crate::create_exception!($module, $py_err, $base, "");
22    };
23    ( $module:expr, $py_err: ident, $base: ty, $doc: expr ) => {
24        $crate::pyo3::create_exception!($module, $py_err, $base, $doc);
25
26        #[cfg(feature = "stubs")]
27        impl $crate::pyo3_stub_gen::PyStubType for $py_err {
28            fn type_output() -> $crate::pyo3_stub_gen::TypeInfo {
29                $crate::pyo3_stub_gen::TypeInfo::locally_defined(
30                    stringify!($py_err),
31                    stringify!($module).into(),
32                )
33            }
34        }
35
36        #[cfg(feature = "stubs")]
37        $crate::pyo3_stub_gen::inventory::submit! {
38            $crate::pyo3_stub_gen::type_info::PyClassInfo {
39                pyclass_name: stringify!($py_err),
40                struct_id: ::std::any::TypeId::of::<$py_err>,
41                getters: &[],
42                setters: &[],
43                module: Some(stringify!($module)),
44                doc: $doc,
45                bases: &[|| <$base as $crate::pyo3_stub_gen::PyStubType>::type_output()],
46                has_eq: false,
47                has_ord: false,
48                has_hash: false,
49                has_str: false,
50                subclass: true,
51            }
52        }
53    };
54}
55
56/// Create a Python exception and a conversion from its Rust type.
57/// Note that the exception class must still be added to the module.
58#[macro_export]
59macro_rules! exception {
60    ( $rust_err: ty, $module:expr, $py_err: ident, $base: ty $(, $doc: expr)? ) => {
61        $crate::create_exception!( $module, $py_err, $base $(, $doc)? );
62
63        #[doc = concat!(
64            "Convert a Rust ",
65            "`", stringify!($rust_err), "`",
66            " into a Python ",
67            "`", stringify!($py_err), "`."
68        )]
69        impl ::std::convert::From<$rust_err> for $crate::pyo3::PyErr {
70            fn from(err: $rust_err) -> Self {
71                $py_err::new_err(err.to_string())
72            }
73        }
74    };
75}