GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Unify `PyObject` dereferencing in c-api by bschoenmaeckers · Pull Request #8292 · RustPython/RustPython

Unify PyObject dereferencing in c-api #8292

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
youknowone merged 5 commits into RustPython:main from bschoenmaeckers:a-api-ffi-helper
Sep 24, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

Unify PyObject dereferencing in c-api #8292

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
5 commits
Select commit Hold shift + click to select a range
e220eb1
Add `FfiPtrExt` for uniform pointer dereferences
bschoenmaeckers Jul 16, 2026
c5f7e2a
Panic on NULL ptrs
bschoenmaeckers Jul 16, 2026
40f819f
capi: import type_name from core, not std
youknowone Sep 23, 2026
d3e5c3f
Use `assume_owned_or_err` in PyGetSetDef
bschoenmaeckers Sep 24, 2026
51216ec
Update latest code
bschoenmaeckers Sep 24, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

61 changes: 31 additions & 30 deletions 61 crates/capi/src/abstract_.rs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::util::CStrExt;
use crate::util::FfiPtrExt;
use crate::{PyObject, pystate::with_vm};
use alloc::slice;
use core::ffi::{c_char, c_int};
Expand Down Expand Up @@ -44,10 +45,10 @@ pub unsafe extern "C" fn PyObject_Call(
kwargs: *mut PyObject,
) -> *mut PyObject {
with_vm(|vm| {
let callable = unsafe { &*callable };
let args = tuple_to_args(unsafe { &*args }.try_downcast_ref::<PyTuple>(vm)?);
let callable = unsafe { callable.assume_borrowed() };
let args = tuple_to_args(unsafe { args.assume_borrowed_and_cast::<PyTuple>(vm) }?);

let kwargs: Option<KwArgs> = unsafe { kwargs.as_ref() }
let kwargs: Option<KwArgs> = unsafe { kwargs.assume_borrowed_or_opt() }
.map(|kwargs| dict_to_kwargs(vm, kwargs.try_downcast_ref::<PyDict>(vm)?))
.transpose()?;

Expand All @@ -57,7 +58,7 @@ pub unsafe extern "C" fn PyObject_Call(

#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyObject_CallNoArgs(callable: *mut PyObject) -> *mut PyObject {
with_vm(|vm| unsafe { &*callable }.call((), vm))
with_vm(|vm| unsafe { callable.assume_borrowed() }.call((), vm))
}

#[unsafe(no_mangle)]
Expand All @@ -66,8 +67,8 @@ pub unsafe extern "C" fn PyObject_CallObject(
args: *mut PyObject,
) -> *mut PyObject {
with_vm(|vm| {
let callable = unsafe { &*callable };
if let Some(args) = unsafe { args.as_ref() } {
let callable = unsafe { callable.assume_borrowed() };
if let Some(args) = unsafe { args.assume_borrowed_or_opt() } {
callable.call(tuple_to_args(args.try_downcast_ref::<PyTuple>(vm)?), vm)
} else {
callable.call((), vm)
Expand All @@ -87,7 +88,7 @@ pub unsafe extern "C" fn PyObject_Vectorcall(

let kwnames: Option<&[PyObjectRef]> = unsafe {
kwnames
.as_ref()
.assume_borrowed_or_opt()
.map(|tuple| Ok(&***tuple.try_downcast_ref::<PyTuple>(vm)?))
.transpose()?
};
Expand All @@ -98,11 +99,11 @@ pub unsafe extern "C" fn PyObject_Vectorcall(
} else {
unsafe { slice::from_raw_parts(args, args_len) }
.iter()
.map(|arg| unsafe { &**arg }.to_owned())
.map(|arg| unsafe { arg.assume_borrowed() }.to_owned())
.collect::<Vec<_>>()
};

let callable = unsafe { &*callable };
let callable = unsafe { callable.assume_borrowed() };
callable.vectorcall(args, num_positional_args, kwnames, vm)
})
}
Expand All @@ -125,8 +126,8 @@ pub unsafe extern "C" fn PyObject_VectorcallMethod(
.split_first()
.expect("args_len > 0 should guarantee a receiver");

let method_name = unsafe { (&*name).try_downcast_ref::<PyStr>(vm)? };
let callable = unsafe { (&**receiver).get_attr(method_name, vm)? };
let method_name = unsafe { name.assume_borrowed_and_cast::<PyStr>(vm)? };
let callable = unsafe { receiver.assume_borrowed().get_attr(method_name, vm)? };

Ok(unsafe {
PyObject_Vectorcall(
Expand All @@ -146,14 +147,14 @@ pub unsafe extern "C" fn PyVectorcall_Call(
kwargs: *mut PyObject,
) -> *mut PyObject {
with_vm(|vm| {
let callable = unsafe { &*callable };
let tuple = unsafe { &*tuple }.try_downcast_ref::<PyTuple>(vm)?;
let callable = unsafe { callable.assume_borrowed() };
let tuple = unsafe { tuple.assume_borrowed_and_cast::<PyTuple>(vm) }?;

let mut args = tuple.iter().cloned().collect::<Vec<_>>();
let num_positional_args = args.len();

let mut kwnames = Vec::new();
if let Some(kwargs) = unsafe { kwargs.as_ref() } {
if let Some(kwargs) = unsafe { kwargs.assume_borrowed_or_opt() } {
let kwargs = kwargs.try_downcast_ref::<PyDict>(vm)?;
for (key, value) in kwargs.items_vec() {
let key = key
Expand All @@ -178,8 +179,8 @@ pub unsafe extern "C" fn PyVectorcall_Call(
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyObject_GetItem(obj: *mut PyObject, key: *mut PyObject) -> *mut PyObject {
with_vm(|vm| {
let obj = unsafe { &*obj };
let key = unsafe { &*key };
let obj = unsafe { obj.assume_borrowed() };
let key = unsafe { key.assume_borrowed() };
obj.get_item(key, vm)
})
}
Expand All @@ -191,26 +192,26 @@ pub unsafe extern "C" fn PyObject_SetItem(
value: *mut PyObject,
) -> c_int {
with_vm(|vm| {
let obj = unsafe { &*obj };
let key = unsafe { &*key };
let value = unsafe { &*value }.to_owned();
let obj = unsafe { obj.assume_borrowed() };
let key = unsafe { key.assume_borrowed() };
let value = unsafe { value.assume_borrowed() }.to_owned();
obj.set_item(key, value, vm)
})
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyObject_DelItem(obj: *mut PyObject, key: *mut PyObject) -> c_int {
with_vm(|vm| {
let obj = unsafe { &*obj };
let key = unsafe { &*key };
let obj = unsafe { obj.assume_borrowed() };
let key = unsafe { key.assume_borrowed() };
obj.del_item(key, vm)
})
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyObject_DelItemString(obj: *mut PyObject, key: *const c_char) -> c_int {
with_vm(|vm| {
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
let key = unsafe { key.try_as_str(vm) }?;
obj.del_item(key, vm)
})
Expand All @@ -222,8 +223,8 @@ pub unsafe extern "C" fn PyObject_Format(
format_spec: *mut PyObject,
) -> *mut PyObject {
with_vm(|vm| {
let obj = unsafe { &*obj };
let spec = unsafe { format_spec.as_ref() }
let obj = unsafe { obj.assume_borrowed() };
let spec = unsafe { format_spec.assume_borrowed_or_opt() }
.map(|spec| spec.try_downcast_ref::<PyStr>(vm))
.transpose()?
.unwrap_or_else(|| vm.ctx.empty_str);
Expand All @@ -234,25 +235,25 @@ pub unsafe extern "C" fn PyObject_Format(
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyObject_IsSubclass(derived: *mut PyObject, cls: *mut PyObject) -> c_int {
with_vm(|vm| {
let derived = unsafe { &*derived };
let cls = unsafe { &*cls };
let derived = unsafe { derived.assume_borrowed() };
let cls = unsafe { cls.assume_borrowed() };
derived.is_subclass(cls, vm)
})
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyObject_IsInstance(inst: *mut PyObject, cls: *mut PyObject) -> c_int {
with_vm(|vm| {
let inst = unsafe { &*inst };
let cls = unsafe { &*cls };
let inst = unsafe { inst.assume_borrowed() };
let cls = unsafe { cls.assume_borrowed() };
inst.is_instance(cls, vm)
})
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyObject_Size(obj: *mut PyObject) -> isize {
with_vm(|vm| {
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
obj.length(vm)
})
}
Expand All @@ -264,7 +265,7 @@ pub unsafe extern "C" fn PyObject_Length(obj: *mut PyObject) -> isize {

#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyObject_Type(obj: *mut PyObject) -> *mut PyObject {
with_vm(|_vm| unsafe { &*obj }.obj_type())
with_vm(|_vm| unsafe { obj.assume_borrowed() }.obj_type())
}

#[cfg(test)]
Expand Down
20 changes: 10 additions & 10 deletions 20 crates/capi/src/abstract_/iter.rs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::util::FfiPtrExt;
use crate::{PyObject, pystate::with_vm};
use core::ffi::c_int;
use rustpython_vm::PyObjectRef;
Expand All @@ -6,13 +7,13 @@ use rustpython_vm::protocol::{PyIter, PyIterReturn};

#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyIter_Check(obj: *mut PyObject) -> c_int {
with_vm(|_vm| Ok(PyIter::check(unsafe { &*obj })))
with_vm(|_vm| Ok(PyIter::check(unsafe { obj.assume_borrowed() })))
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyAIter_Check(obj: *mut PyObject) -> c_int {
with_vm(|vm| {
Ok(unsafe { &*obj }
Ok(unsafe { obj.assume_borrowed() }
.class()
.has_attr(rustpython_vm::identifier!(vm, __anext__)))
})
Expand All @@ -21,14 +22,14 @@ pub unsafe extern "C" fn PyAIter_Check(obj: *mut PyObject) -> c_int {
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyObject_GetIter(obj: *mut PyObject) -> *mut PyObject {
with_vm(|vm| {
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
obj.get_iter(vm).map(PyObjectRef::from)
})
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyObject_GetAIter(obj: *mut PyObject) -> *mut PyObject {
with_vm(|vm| unsafe { &*obj }.get_aiter(vm))
with_vm(|vm| unsafe { obj.assume_borrowed() }.get_aiter(vm))
}

#[unsafe(no_mangle)]
Expand All @@ -38,7 +39,7 @@ pub unsafe extern "C" fn PyIter_NextItem(iter: *mut PyObject, item: *mut *mut Py
*item = core::ptr::null_mut();
}

let iter = PyIter::new(unsafe { &*iter });
let iter = PyIter::new(unsafe { iter.assume_borrowed() });
match iter.next(vm)? {
PyIterReturn::Return(next_item) => {
unsafe {
Expand All @@ -54,7 +55,7 @@ pub unsafe extern "C" fn PyIter_NextItem(iter: *mut PyObject, item: *mut *mut Py
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyIter_Next(iter: *mut PyObject) -> *mut PyObject {
with_vm(|vm| {
let iter = PyIter::new(unsafe { &*iter });
let iter = PyIter::new(unsafe { iter.assume_borrowed() });
match iter.next(vm)? {
PyIterReturn::Return(next_item) => Ok(next_item.into_raw().as_ptr()),
PyIterReturn::StopIteration(_) => Ok(core::ptr::null_mut()),
Expand All @@ -73,14 +74,13 @@ pub unsafe extern "C" fn PyIter_Send(
*presult = core::ptr::null_mut();
}

let iter_obj = unsafe { &*iter };
let arg_obj = unsafe { &*arg };
let iter_obj = unsafe { iter.assume_borrowed() };
let arg_obj = unsafe { arg.assume_borrowed() };

let ret = if vm.is_none(arg_obj) {
PyIter::new(iter_obj).next(vm)?
} else {
iter_obj
.try_downcast_ref::<PyGenerator>(vm)?
unsafe { iter.assume_borrowed_and_cast::<PyGenerator>(vm) }?
.as_coro()
.send(iter_obj, arg_obj.to_owned(), vm)?
};
Expand Down
35 changes: 18 additions & 17 deletions 35 crates/capi/src/abstract_/mapping.rs
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
use crate::util::CStrExt;
use crate::util::FfiPtrExt;
use crate::{PyObject, pystate::with_vm};
use core::ffi::{c_char, c_int};
use rustpython_vm::AsObject;

#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyMapping_Check(obj: *mut PyObject) -> c_int {
with_vm(|_vm| {
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
Ok(obj.mapping_unchecked().check())
})
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyMapping_Size(obj: *mut PyObject) -> isize {
with_vm(|vm| {
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
obj.try_mapping(vm)?.length(vm)
})
}
Expand All @@ -27,7 +28,7 @@ pub unsafe extern "C" fn PyMapping_Length(obj: *mut PyObject) -> isize {
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyMapping_Keys(obj: *mut PyObject) -> *mut PyObject {
with_vm(|vm| {
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
let keys = obj.try_mapping(vm)?.keys(vm)?;
let iter = keys.get_iter(vm)?;
Ok(vm.ctx.new_list(iter.try_to_value(vm)?))
Expand All @@ -37,7 +38,7 @@ pub unsafe extern "C" fn PyMapping_Keys(obj: *mut PyObject) -> *mut PyObject {
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyMapping_Values(obj: *mut PyObject) -> *mut PyObject {
with_vm(|vm| {
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
let values = obj.try_mapping(vm)?.values(vm)?;
let iter = values.get_iter(vm)?;
Ok(vm.ctx.new_list(iter.try_to_value(vm)?))
Expand All @@ -47,7 +48,7 @@ pub unsafe extern "C" fn PyMapping_Values(obj: *mut PyObject) -> *mut PyObject {
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyMapping_Items(obj: *mut PyObject) -> *mut PyObject {
with_vm(|vm| {
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
let items = obj.try_mapping(vm)?.items(vm)?;
let iter = items.get_iter(vm)?;
Ok(vm.ctx.new_list(iter.try_to_value(vm)?))
Expand All @@ -60,7 +61,7 @@ pub unsafe extern "C" fn PyMapping_GetItemString(
key: *const c_char,
) -> *mut PyObject {
with_vm(|vm| {
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
let key = unsafe { key.try_as_str(vm) }?;
obj.get_item(key, vm)
})
Expand All @@ -76,8 +77,8 @@ pub unsafe extern "C" fn PyMapping_GetOptionalItem(
unsafe {
*result = core::ptr::null_mut();
}
let obj = unsafe { &*obj };
let key = unsafe { &*key };
let obj = unsafe { obj.assume_borrowed() };
let key = unsafe { key.assume_borrowed() };

match obj.get_item(key, vm) {
Ok(value) => {
Expand All @@ -102,7 +103,7 @@ pub unsafe extern "C" fn PyMapping_GetOptionalItemString(
unsafe {
*result = core::ptr::null_mut();
}
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
let key = unsafe { key.try_as_str(vm) }?;

match obj.get_item(key, vm) {
Expand All @@ -121,16 +122,16 @@ pub unsafe extern "C" fn PyMapping_GetOptionalItemString(
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyMapping_HasKey(obj: *mut PyObject, key: *mut PyObject) -> c_int {
with_vm(|vm| {
let obj = unsafe { &*obj };
let key = unsafe { &*key };
let obj = unsafe { obj.assume_borrowed() };
let key = unsafe { key.assume_borrowed() };
obj.get_item(key, vm).is_ok()
})
}

#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyMapping_HasKeyString(obj: *mut PyObject, key: *const c_char) -> c_int {
with_vm(|vm| {
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
if let Ok(key) = unsafe { key.try_as_str(vm) } {
obj.get_item(key, vm).is_ok()
} else {
Expand All @@ -145,8 +146,8 @@ pub unsafe extern "C" fn PyMapping_HasKeyWithError(
key: *mut PyObject,
) -> c_int {
with_vm(|vm| {
let obj = unsafe { &*obj };
let key = unsafe { &*key };
let obj = unsafe { obj.assume_borrowed() };
let key = unsafe { key.assume_borrowed() };

match obj.get_item(key, vm) {
Ok(_) => Ok(true),
Expand All @@ -162,7 +163,7 @@ pub unsafe extern "C" fn PyMapping_HasKeyStringWithError(
key: *const c_char,
) -> c_int {
with_vm(|vm| {
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
let key = unsafe { key.try_as_str(vm) }?;

match obj.get_item(key, vm) {
Expand All @@ -180,9 +181,9 @@ pub unsafe extern "C" fn PyMapping_SetItemString(
value: *mut PyObject,
) -> c_int {
with_vm(|vm| {
let obj = unsafe { &*obj };
let obj = unsafe { obj.assume_borrowed() };
let key = unsafe { key.try_as_str(vm) }?;
let value = unsafe { &*value }.to_owned();
let value = unsafe { value.assume_borrowed() }.to_owned();
obj.set_item(key, value, vm)
})
}
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.