1use crate::object::define_py_check;
2use crate::util::{CStrExt, FfiPtrExt};
3use crate::{PyObject, pystate::with_vm};
4use core::convert::Infallible;
5use core::ffi::{c_char, c_int};
6use core::slice;
7use rustpython_vm::builtins::{PyBaseException, PyTraceback, PyTuple, PyType};
8use rustpython_vm::convert::IntoObject;
9use rustpython_vm::exceptions::ExceptionZoo;
10use rustpython_vm::{AsObject, PyResult};
11
12macro_rules! define_exception_statics {
13 ($( $(#[$meta:meta])* $export:ident => $exc:ident ),* $(,)?) => {
14 $(
15 $(#[$meta])*
16 #[unsafe(no_mangle)]
17 pub static mut $export: *mut PyObject = core::ptr::null_mut();
18 )*
19
20 #[allow(static_mut_refs)]
21 pub(crate) unsafe fn init_exception_statics(zoo: &'static ExceptionZoo) {
22 unsafe {
23 $(
24 $export = zoo.$exc.as_object().as_raw().cast_mut();
25 )*
26 }
27 }
28 };
29}
30
31define_exception_statics! {
32 PyExc_BaseException => base_exception_type,
33 PyExc_BaseExceptionGroup => base_exception_group,
34 PyExc_SystemExit => system_exit,
35 PyExc_KeyboardInterrupt => keyboard_interrupt,
36 PyExc_GeneratorExit => generator_exit,
37 PyExc_Exception => exception_type,
38 PyExc_StopIteration => stop_iteration,
39 PyExc_StopAsyncIteration => stop_async_iteration,
40 PyExc_ArithmeticError => arithmetic_error,
41 PyExc_FloatingPointError => floating_point_error,
42 PyExc_SystemError => system_error,
43 PyExc_TypeError => type_error,
44 PyExc_OverflowError => overflow_error,
45 PyExc_ZeroDivisionError => zero_division_error,
46 PyExc_AssertionError => assertion_error,
47 PyExc_IndexError => index_error,
48 PyExc_KeyError => key_error,
49 PyExc_LookupError => lookup_error,
50 PyExc_AttributeError => attribute_error,
51 PyExc_BufferError => buffer_error,
52 PyExc_EOFError => eof_error,
53 PyExc_ImportError => import_error,
54 PyExc_ModuleNotFoundError => module_not_found_error,
55 PyExc_MemoryError => memory_error,
56 PyExc_NameError => name_error,
57 PyExc_UnboundLocalError => unbound_local_error,
58 PyExc_OSError => os_error,
59 PyExc_BlockingIOError => blocking_io_error,
60 PyExc_ChildProcessError => child_process_error,
61 PyExc_ConnectionError => connection_error,
62 PyExc_BrokenPipeError => broken_pipe_error,
63 PyExc_ConnectionAbortedError => connection_aborted_error,
64 PyExc_ConnectionRefusedError => connection_refused_error,
65 PyExc_ConnectionResetError => connection_reset_error,
66 PyExc_FileExistsError => file_exists_error,
67 PyExc_FileNotFoundError => file_not_found_error,
68 PyExc_InterruptedError => interrupted_error,
69 PyExc_IsADirectoryError => is_a_directory_error,
70 PyExc_NotADirectoryError => not_a_directory_error,
71 PyExc_PermissionError => permission_error,
72 PyExc_ProcessLookupError => process_lookup_error,
73 PyExc_TimeoutError => timeout_error,
74 PyExc_ReferenceError => reference_error,
75 PyExc_RuntimeError => runtime_error,
76 PyExc_NotImplementedError => not_implemented_error,
77 PyExc_RecursionError => recursion_error,
78 PyExc_SyntaxError => syntax_error,
79 PyExc_IndentationError => indentation_error,
80 PyExc_TabError => tab_error,
81 PyExc_ValueError => value_error,
82 PyExc_UnicodeError => unicode_error,
83 PyExc_UnicodeDecodeError => unicode_decode_error,
84 PyExc_UnicodeEncodeError => unicode_encode_error,
85 PyExc_UnicodeTranslateError => unicode_translate_error,
86 PyExc_Warning => warning,
87 PyExc_DeprecationWarning => deprecation_warning,
88 PyExc_PendingDeprecationWarning => pending_deprecation_warning,
89 PyExc_RuntimeWarning => runtime_warning,
90 PyExc_SyntaxWarning => syntax_warning,
91 PyExc_UserWarning => user_warning,
92 PyExc_FutureWarning => future_warning,
93 PyExc_ImportWarning => import_warning,
94 PyExc_UnicodeWarning => unicode_warning,
95 PyExc_BytesWarning => bytes_warning,
96 PyExc_ResourceWarning => resource_warning,
97 PyExc_EncodingWarning => encoding_warning,
98}
99
100define_py_check!(fn PyExceptionInstance_Check, exceptions.base_exception_type);
101
102#[unsafe(no_mangle)]
103pub extern "C" fn PyErr_Occurred() -> *mut PyObject {
104 with_vm(|vm| {
105 vm.current_exception()
106 .map(|exc| exc.class().as_object().as_raw())
107 .unwrap_or_default()
108 })
109}
110
111#[unsafe(no_mangle)]
112pub extern "C" fn PyErr_GetRaisedException() -> *mut PyObject {
113 with_vm(|vm| {
114 vm.take_raised_exception()
115 .map(|exc| exc.into_object().into_raw().as_ptr())
116 .unwrap_or_default()
117 })
118}
119
120#[unsafe(no_mangle)]
121pub unsafe extern "C" fn PyErr_SetRaisedException(exc: *mut PyObject) {
122 with_vm(|vm| {
123 let exception =
124 unsafe { exc.assume_owned_or_opt() }.map(|exc| unsafe { exc.downcast_unchecked() });
125 vm.set_exception(exception);
126 })
127}
128
129#[unsafe(no_mangle)]
130pub unsafe extern "C" fn PyErr_SetObject(exception: *mut PyObject, value: *mut PyObject) {
131 with_vm::<PyResult<Infallible>, _>(|vm| {
132 let exc_type = unsafe { exception.assume_borrowed() }.to_owned();
133 let exc_val = unsafe { value.assume_borrowed() }.to_owned();
134
135 let normalized = vm.normalize_exception(exc_type, exc_val, vm.ctx.none())?;
136 Err(normalized)
137 })
138}
139
140#[unsafe(no_mangle)]
141pub unsafe extern "C" fn PyErr_SetString(exception: *mut PyObject, message: *const c_char) {
142 with_vm::<PyResult<Infallible>, _>(|vm| {
143 let exc_type = unsafe { exception.assume_borrowed_and_cast::<PyType>(vm) }?;
144 let message = unsafe { message.try_as_str(vm) }?;
145
146 let exc = vm.invoke_exception(exc_type, vec![vm.ctx.new_str(message).into_object()])?;
147
148 Err(exc)
149 })
150}
151
152#[unsafe(no_mangle)]
153pub extern "C" fn PyErr_PrintEx(_set_sys_last_vars: c_int) {
154 with_vm(|vm| {
155 let exception = vm
156 .take_raised_exception()
157 .expect("No exception set in PyErr_PrintEx");
158
159 vm.print_exception(&exception);
160 })
161}
162
163#[unsafe(no_mangle)]
164pub unsafe extern "C" fn PyErr_DisplayException(exc: *mut PyObject) {
165 with_vm(|vm| {
166 let exception = unsafe { exc.assume_borrowed() }
167 .downcast_ref::<PyBaseException>()
168 .expect("PyErr_DisplayException exc must be an exception instance");
169
170 vm.print_exception(exception);
171 })
172}
173
174#[unsafe(no_mangle)]
175pub unsafe extern "C" fn PyErr_WriteUnraisable(obj: *mut PyObject) {
176 with_vm(|vm| {
177 let exception = vm
178 .take_raised_exception()
179 .expect("No exception set in PyErr_WriteUnraisable");
180
181 let object =
182 unsafe { vm.unwrap_or_none(obj.assume_borrowed_or_opt().map(ToOwned::to_owned)) };
183
184 vm.run_unraisable(exception, None, object)
185 })
186}
187
188#[unsafe(no_mangle)]
189pub unsafe extern "C" fn PyExceptionClass_Check(obj: *mut PyObject) -> c_int {
190 with_vm(|vm| unsafe {
191 obj.assume_borrowed_or_opt()
192 .and_then(|obj| obj.downcast_ref::<PyType>())
193 .is_some_and(|ty| ty.is_subtype(vm.ctx.exceptions.base_exception_type))
194 })
195}
196
197#[unsafe(no_mangle)]
198pub unsafe extern "C" fn PyErr_NewException(
199 name: *const c_char,
200 base: *mut PyObject,
201 dict: *mut PyObject,
202) -> *mut PyObject {
203 with_vm(|vm| {
204 let (module, name) = unsafe { name.try_as_str(vm) }
205 .expect("Exception name is not valid UTF-8")
206 .rsplit_once('.')
207 .expect("Exception name must be of the form 'module.ExceptionName'");
208
209 let bases = unsafe { base.assume_borrowed_or_opt() }.map(|bases| {
210 if let Some(ty) = bases.downcast_ref::<PyType>() {
211 vec![ty.to_owned()]
212 } else if let Some(tuple) = bases.downcast_ref::<PyTuple>() {
213 tuple
214 .as_slice()
215 .iter()
216 .map(|item| item.to_owned().downcast())
217 .collect::<Result<Vec<_>, _>>()
218 .expect("PyErr_NewException base tuple must contain only types")
219 } else {
220 panic!("PyErr_NewException base must be a type or a tuple of types");
221 }
222 });
223
224 assert!(
225 dict.is_null(),
226 "PyErr_NewException with non-null dict is not supported yet"
227 );
228
229 vm.ctx.new_exception_type(module, name, bases)
230 })
231}
232
233#[unsafe(no_mangle)]
234pub unsafe extern "C" fn PyErr_NewExceptionWithDoc(
235 name: *const c_char,
236 _doc: *const c_char,
237 base: *mut PyObject,
238 dict: *mut PyObject,
239) -> *mut PyObject {
240 unsafe { PyErr_NewException(name, base, dict) }
241}
242
243#[unsafe(no_mangle)]
244pub unsafe extern "C" fn PyErr_GivenExceptionMatches(
245 given: *mut PyObject,
246 exc: *mut PyObject,
247) -> c_int {
248 with_vm(|vm| {
249 let given = unsafe { given.assume_borrowed() };
250 let exc = unsafe { exc.assume_borrowed() };
251
252 given.is_subclass(exc, vm)
253 })
254}
255
256#[unsafe(no_mangle)]
257pub unsafe extern "C" fn PyException_GetTraceback(exc: *mut PyObject) -> *mut PyObject {
258 with_vm(|vm| {
259 let exc = unsafe { exc.assume_borrowed_and_cast::<PyBaseException>(vm) }?;
260 let tb = exc
261 .traceback()
262 .map(|tb| tb.into_object().into_raw().as_ptr())
263 .unwrap_or_default();
264 Ok(tb)
265 })
266}
267
268#[unsafe(no_mangle)]
269pub unsafe extern "C" fn PyException_GetCause(exc: *mut PyObject) -> *mut PyObject {
270 with_vm(|vm| {
271 let exc = unsafe { exc.assume_borrowed_and_cast::<PyBaseException>(vm) }?;
272 let cause = exc
273 .__cause__()
274 .map(|cause| cause.into_object().into_raw().as_ptr())
275 .unwrap_or_default();
276 Ok(cause)
277 })
278}
279
280#[unsafe(no_mangle)]
281pub unsafe extern "C" fn PyException_GetContext(exc: *mut PyObject) -> *mut PyObject {
282 with_vm(|vm| {
283 let exc = unsafe { exc.assume_borrowed_and_cast::<PyBaseException>(vm) }?;
284 let context = exc
285 .__context__()
286 .map(|context| context.into_object().into_raw().as_ptr())
287 .unwrap_or_default();
288 Ok(context)
289 })
290}
291
292#[unsafe(no_mangle)]
293pub unsafe extern "C" fn PyException_SetCause(exc: *mut PyObject, cause: *mut PyObject) {
294 with_vm(|vm| {
295 let exc = unsafe { exc.assume_borrowed_and_cast::<PyBaseException>(vm) }?;
296 let cause =
297 unsafe { cause.assume_owned_or_opt() }.map(|obj| unsafe { obj.downcast_unchecked() });
298 exc.set_cause(cause);
299 Ok(())
300 })
301}
302
303#[unsafe(no_mangle)]
304pub unsafe extern "C" fn PyException_SetContext(exc: *mut PyObject, context: *mut PyObject) {
305 with_vm(|vm| {
306 let exc = unsafe { exc.assume_borrowed_and_cast::<PyBaseException>(vm) }?;
307 let context =
308 unsafe { context.assume_owned_or_opt() }.map(|obj| unsafe { obj.downcast_unchecked() });
309 exc.set_context(context);
310 Ok(())
311 })
312}
313
314#[unsafe(no_mangle)]
315pub unsafe extern "C" fn PyUnicodeDecodeError_Create(
316 encoding: *const c_char,
317 object: *const c_char,
318 length: isize,
319 start: isize,
320 end: isize,
321 reason: *const c_char,
322) -> *mut PyObject {
323 with_vm(|vm| {
324 let encoding = unsafe { encoding.try_as_str(vm) }?;
325 let reason = unsafe { reason.try_as_str(vm) }?;
326 let length: usize = length
327 .try_into()
328 .map_err(|_| vm.new_system_error("length must be non-negative"))?;
329 let start: usize = start
330 .try_into()
331 .map_err(|_| vm.new_system_error("start must be non-negative"))?;
332 let end: usize = end
333 .try_into()
334 .map_err(|_| vm.new_system_error("end must be non-negative"))?;
335
336 let bytes = if object.is_null() {
337 if length != 0 {
338 return Err(vm.new_system_error(
339 "PyUnicodeDecodeError_Create called with null object and non-zero length",
340 ));
341 }
342 Vec::new()
343 } else {
344 unsafe { slice::from_raw_parts(object.cast::<u8>(), length) }.to_vec()
345 };
346
347 let exc = vm.new_unicode_decode_error(
348 vm.ctx.new_str(encoding),
349 vm.ctx.new_bytes(bytes),
350 start,
351 end,
352 vm.ctx.new_str(reason),
353 );
354 Ok(exc)
355 })
356}
357
358#[unsafe(no_mangle)]
359pub unsafe extern "C" fn PyException_SetTraceback(exc: *mut PyObject, tb: *mut PyObject) -> c_int {
360 with_vm(|vm| {
361 let exc = unsafe { exc.assume_borrowed_and_cast::<PyBaseException>(vm) }?;
362 let traceback = match unsafe { tb.assume_borrowed_or_opt() }.map(ToOwned::to_owned) {
363 None => None,
364 Some(obj) if vm.is_none(&obj) => None,
365 Some(obj) => Some(
366 obj.downcast::<PyTraceback>()
367 .map_err(|_| vm.new_type_error("__traceback__ must be a traceback or None"))?,
368 ),
369 };
370 exc.set_traceback(traceback);
371 Ok(())
372 })
373}
374
375#[cfg(test)]
376mod tests {
377 use pyo3::PyTypeInfo;
378 use pyo3::create_exception;
379 use pyo3::exceptions::{PyException, PyTypeError};
380 use pyo3::prelude::*;
381
382 #[test]
383 fn raised_exception() {
384 Python::attach(|py| {
385 PyTypeError::new_err(py.None()).restore(py);
386 assert!(PyErr::occurred(py));
387 assert!(PyErr::take(py).is_some());
388 assert!(!PyErr::occurred(py));
389 })
390 }
391
392 #[test]
393 fn error_is_instance() {
394 Python::attach(|py| {
395 let err = PyTypeError::new_err(py.None());
396 assert!(err.is_instance_of::<PyTypeError>(py));
397 })
398 }
399
400 #[test]
401 fn new_exception_type() {
402 create_exception!(my_module, MyError, PyException, "Some description.");
403
404 Python::attach(|py| {
405 let exc = MyError::new_err("This is a new exception");
406 assert!(exc.is_instance_of::<MyError>(py));
407 let exc_type = MyError::type_object(py);
408 assert_eq!(
409 exc_type.fully_qualified_name().unwrap(),
410 "my_module.MyError"
411 );
412 })
413 }
414}