1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use std;
use python::{PythonObject, ToPythonPointer, Python, PythonObjectDowncastError,
PythonObjectWithTypeObject, PyClone, PyDrop};
use objects::{PyObject, PyType, exc};
#[cfg(feature="python27-sys")]
use objects::oldstyle::PyClass;
use ffi;
use libc;
use std::ptr;
use libc::c_char;
use conversion::ToPyObject;
use std::ffi::CString;
#[macro_export]
macro_rules! py_exception {
($module: ident, $name: ident, $base: ty) => {
pub struct $name($crate::PyObject);
pyobject_newtype!($name);
impl $name {
pub fn new<'p, T: $crate::ToPyObject>(py: $crate::Python<'p>, args: T) -> $crate::PyErr {
$crate::PyErr::new::<$name, T>(py, args)
}
}
impl $crate::PythonObjectWithCheckedDowncast for $name {
#[inline]
fn downcast_from<'p>(py: $crate::Python<'p>, obj: $crate::PyObject)
-> Result<$name, $crate::PythonObjectDowncastError<'p>>
{
if <$name as $crate::PythonObjectWithTypeObject>::type_object(py).is_instance(py, &obj) {
Ok(unsafe { $crate::PythonObject::unchecked_downcast_from(obj) })
} else {
Err($crate::PythonObjectDowncastError(py))
}
}
#[inline]
fn downcast_borrow_from<'a, 'p>(py: $crate::Python<'p>, obj: &'a $crate::PyObject)
-> Result<&'a $name, $crate::PythonObjectDowncastError<'p>>
{
if <$name as $crate::PythonObjectWithTypeObject>::type_object(py).is_instance(py, obj) {
Ok(unsafe { $crate::PythonObject::unchecked_downcast_borrow_from(obj) })
} else {
Err($crate::PythonObjectDowncastError(py))
}
}
}
impl $crate::PythonObjectWithTypeObject for $name {
#[inline]
fn type_object(py: $crate::Python) -> $crate::PyType {
unsafe {
static mut type_object: *mut $crate::_detail::ffi::PyTypeObject = 0 as *mut $crate::_detail::ffi::PyTypeObject;
if type_object.is_null() {
type_object = $crate::PyErr::new_type(
py,
concat!(stringify!($module), ".", stringify!($name)),
Some($crate::PythonObject::into_object(py.get_type::<$base>())),
None).as_type_ptr();
}
$crate::PyType::from_type_ptr(py, type_object)
}
}
}
};
($module: ident, $name: ident) => {
py_exception!($module, $name, $crate::exc::Exception);
}
}
#[derive(Debug)]
pub struct PyErr {
pub ptype : PyObject,
pub pvalue : Option<PyObject>,
pub ptraceback : Option<PyObject>
}
pub type PyResult<T> = Result<T, PyErr>;
impl PyErr {
pub fn new<T, V>(py: Python, value: V) -> PyErr
where T: PythonObjectWithTypeObject, V: ToPyObject
{
PyErr::new_helper(py, py.get_type::<T>(), value.to_py_object(py).into_object())
}
#[inline]
pub fn occurred(_ : Python) -> bool {
unsafe { !ffi::PyErr_Occurred().is_null() }
}
pub fn new_type(py: Python, name: &str, base: Option<PyObject>, dict: Option<PyObject>) -> PyType {
let base: *mut ffi::PyObject = match base {
None => ptr::null_mut(),
Some(obj) => obj.steal_ptr()
};
let dict: *mut ffi::PyObject = match dict {
None => ptr::null_mut(),
Some(obj) => obj.steal_ptr()
};
unsafe {
let null_terminated_name = CString::new(name).unwrap();
let ptr: *mut ffi::PyObject = ffi::PyErr_NewException(null_terminated_name.as_ptr() as *mut c_char,
base,
dict);
PyObject::from_borrowed_ptr(py, ptr).unchecked_cast_into::<PyType>()
}
}
pub fn fetch(py : Python) -> PyErr {
unsafe {
let mut ptype : *mut ffi::PyObject = std::mem::uninitialized();
let mut pvalue : *mut ffi::PyObject = std::mem::uninitialized();
let mut ptraceback : *mut ffi::PyObject = std::mem::uninitialized();
ffi::PyErr_Fetch(&mut ptype, &mut pvalue, &mut ptraceback);
PyErr::new_from_ffi_tuple(py, ptype, pvalue, ptraceback)
}
}
unsafe fn new_from_ffi_tuple(py: Python, ptype: *mut ffi::PyObject, pvalue: *mut ffi::PyObject, ptraceback: *mut ffi::PyObject) -> PyErr {
PyErr {
ptype: if ptype.is_null() {
py.get_type::<exc::SystemError>().into_object()
} else {
PyObject::from_owned_ptr(py, ptype)
},
pvalue: PyObject::from_owned_ptr_opt(py, pvalue),
ptraceback: PyObject::from_owned_ptr_opt(py, ptraceback)
}
}
fn new_helper(_py: Python, ty: PyType, value: PyObject) -> PyErr {
assert!(unsafe { ffi::PyExceptionClass_Check(ty.as_object().as_ptr()) } != 0);
PyErr {
ptype: ty.into_object(),
pvalue: Some(value),
ptraceback: None
}
}
pub fn from_instance<O>(py: Python, obj: O) -> PyErr where O: PythonObject {
PyErr::from_instance_helper(py, obj.into_object())
}
fn from_instance_helper(py: Python, obj: PyObject) -> PyErr {
if unsafe { ffi::PyExceptionInstance_Check(obj.as_ptr()) } != 0 {
PyErr {
ptype: unsafe { PyObject::from_borrowed_ptr(py, ffi::PyExceptionInstance_Class(obj.as_ptr())) },
pvalue: Some(obj),
ptraceback: None
}
} else if unsafe { ffi::PyExceptionClass_Check(obj.as_ptr()) } != 0 {
PyErr {
ptype: obj,
pvalue: None,
ptraceback: None
}
} else {
PyErr {
ptype: py.get_type::<exc::TypeError>().into_object(),
pvalue: Some("exceptions must derive from BaseException".to_py_object(py).into_object()),
ptraceback: None
}
}
}
#[inline]
pub fn new_lazy_init(exc: PyType, value: Option<PyObject>) -> PyErr {
PyErr {
ptype: exc.into_object(),
pvalue: value,
ptraceback: None
}
}
pub fn print(self, py: Python) {
self.restore(py);
unsafe { ffi::PyErr_PrintEx(0) }
}
pub fn print_and_set_sys_last_vars(self, py: Python) {
self.restore(py);
unsafe { ffi::PyErr_PrintEx(1) }
}
pub fn matches<T>(&self, py: Python, exc: T) -> bool
where T: ToPyObject
{
exc.with_borrowed_ptr(py, |exc| unsafe {
ffi::PyErr_GivenExceptionMatches(self.ptype.as_ptr(), exc) != 0
})
}
pub fn normalize(&mut self, py: Python) {
unsafe {
std::ptr::write(self, std::ptr::read(self).into_normalized(py));
}
}
fn into_normalized(self, py: Python) -> PyErr {
let PyErr { ptype, pvalue, ptraceback } = self;
let mut ptype = ptype.steal_ptr();
let mut pvalue = pvalue.steal_ptr(py);
let mut ptraceback = ptraceback.steal_ptr(py);
unsafe {
ffi::PyErr_NormalizeException(&mut ptype, &mut pvalue, &mut ptraceback);
PyErr::new_from_ffi_tuple(py, ptype, pvalue, ptraceback)
}
}
#[cfg(feature="python27-sys")]
pub fn get_type(&self, py: Python) -> PyType {
match self.ptype.cast_as::<PyType>(py) {
Ok(t) => t.clone_ref(py),
Err(_) =>
match self.ptype.cast_as::<PyClass>(py) {
Ok(_) => py.get_type::<PyClass>(),
Err(_) => py.None().get_type(py)
}
}
}
#[cfg(not(feature="python27-sys"))]
pub fn get_type(&self, py: Python) -> PyType {
match self.ptype.cast_as::<PyType>(py) {
Ok(t) => t.clone_ref(py),
Err(_) => py.None().get_type(py)
}
}
pub fn instance(&mut self, py: Python) -> PyObject {
self.normalize(py);
match self.pvalue {
Some(ref instance) => instance.clone_ref(py),
None => py.None()
}
}
#[inline]
pub fn restore(self, py: Python) {
let PyErr { ptype, pvalue, ptraceback } = self;
unsafe {
ffi::PyErr_Restore(ptype.steal_ptr(), pvalue.steal_ptr(py), ptraceback.steal_ptr(py))
}
}
pub fn warn(py: Python, category: &PyObject, message: &str, stacklevel: i32) -> PyResult<()> {
let message = CString::new(message).unwrap();
unsafe {
error_on_minusone(py, ffi::PyErr_WarnEx(category.as_ptr(), message.as_ptr(), stacklevel as ffi::Py_ssize_t))
}
}
}
impl PyDrop for PyErr {
fn release_ref(self, py: Python) {
self.ptype.release_ref(py);
self.pvalue.release_ref(py);
self.ptraceback.release_ref(py);
}
}
impl PyClone for PyErr {
fn clone_ref(&self, py: Python) -> PyErr {
PyErr {
ptype: self.ptype.clone_ref(py),
pvalue: self.pvalue.clone_ref(py),
ptraceback: self.ptraceback.clone_ref(py)
}
}
}
impl <'p> std::convert::From<PythonObjectDowncastError<'p>> for PyErr {
fn from(err: PythonObjectDowncastError<'p>) -> PyErr {
PyErr::new_lazy_init(err.0.get_type::<exc::TypeError>(), None)
}
}
#[inline]
pub unsafe fn result_from_owned_ptr(py : Python, p : *mut ffi::PyObject) -> PyResult<PyObject> {
if p.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(PyObject::from_owned_ptr(py, p))
}
}
fn panic_after_error(_py: Python) -> ! {
unsafe { ffi::PyErr_Print(); }
panic!("Python API called failed");
}
#[inline]
pub unsafe fn from_owned_ptr_or_panic(py : Python, p : *mut ffi::PyObject) -> PyObject {
if p.is_null() {
panic_after_error(py);
} else {
PyObject::from_owned_ptr(py, p)
}
}
pub unsafe fn result_cast_from_owned_ptr<T>(py : Python, p : *mut ffi::PyObject) -> PyResult<T>
where T: ::python::PythonObjectWithCheckedDowncast
{
if p.is_null() {
Err(PyErr::fetch(py))
} else {
Ok(try!(PyObject::from_owned_ptr(py, p).cast_into(py)))
}
}
pub unsafe fn cast_from_owned_ptr_or_panic<T>(py : Python, p : *mut ffi::PyObject) -> T
where T: ::python::PythonObjectWithCheckedDowncast
{
if p.is_null() {
panic_after_error(py);
} else {
PyObject::from_owned_ptr(py, p).cast_into(py).unwrap()
}
}
#[inline]
pub fn error_on_minusone(py : Python, result : libc::c_int) -> PyResult<()> {
if result != -1 {
Ok(())
} else {
Err(PyErr::fetch(py))
}
}
#[cfg(test)]
mod tests {
use {Python, PyErr};
use objects::exc;
#[test]
fn set_typeerror() {
let gil = Python::acquire_gil();
let py = gil.python();
PyErr::new_lazy_init(py.get_type::<exc::TypeError>(), None).restore(py);
assert!(PyErr::occurred(py));
drop(PyErr::fetch(py));
}
}