Skip to content

Commit a1a87dc

Browse files
Add macro for type check functions in c-api (#7871)
* Add macro for type check function in c-api * Add `fn` to macro
1 parent ea2a3d9 commit a1a87dc

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

crates/capi/src/object.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,35 @@ use rustpython_vm::{AsObject, Py};
77

88
pub type PyTypeObject = Py<PyType>;
99

10+
macro_rules! define_py_check {
11+
(fn $name:ident, $($ctx_path:ident).+) => {
12+
#[unsafe(no_mangle)]
13+
pub unsafe extern "C" fn $name(obj: *mut crate::PyObject) -> core::ffi::c_int {
14+
crate::pystate::with_vm(|vm| unsafe {
15+
obj
16+
.as_ref()
17+
.map(|obj| obj.class().is_subtype(vm.ctx.$($ctx_path).+))
18+
.unwrap_or_default()
19+
})
20+
}
21+
};
22+
(exact fn $name:ident, $($ctx_path:ident).+) => {
23+
#[unsafe(no_mangle)]
24+
pub unsafe extern "C" fn $name(obj: *mut crate::PyObject) -> core::ffi::c_int {
25+
use rustpython_vm::AsObject;
26+
crate::pystate::with_vm(|vm| unsafe {
27+
obj
28+
.as_ref()
29+
.map(|obj| obj.class().is(vm.ctx.$($ctx_path).+))
30+
.unwrap_or_default()
31+
})
32+
}
33+
};
34+
}
35+
36+
define_py_check!(fn PyType_Check, types.type_type);
37+
define_py_check!(exact fn PyType_CheckExact, types.type_type);
38+
1039
#[unsafe(no_mangle)]
1140
pub unsafe extern "C" fn Py_TYPE(op: *mut PyObject) -> *const PyTypeObject {
1241
unsafe { (*op).class() }
@@ -27,6 +56,15 @@ pub unsafe extern "C" fn PyType_GetFlags(ptr: *const PyTypeObject) -> c_ulong {
2756
ty.slots.flags.bits() as u32 as c_ulong
2857
}
2958

59+
#[unsafe(no_mangle)]
60+
pub unsafe extern "C" fn PyType_IsSubtype(a: *const PyTypeObject, b: *const PyTypeObject) -> c_int {
61+
with_vm(move |_vm| {
62+
let a = unsafe { &*a };
63+
let b = unsafe { &*b };
64+
Ok(a.is_subtype(b))
65+
})
66+
}
67+
3068
#[unsafe(no_mangle)]
3169
pub extern "C" fn Py_GetConstantBorrowed(constant_id: c_uint) -> *mut PyObject {
3270
with_vm(|vm| {

0 commit comments

Comments
 (0)