Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions crates/stdlib/src/csv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ mod _csv {
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
VirtualMachine,
builtins::{PyBaseExceptionRef, PyInt, PyStr, PyType, PyTypeRef, PyUtf8StrRef},
convert::PyListOf,
function::{ArgIterable, ArgumentError, FromArgs, FuncArgs, OptionalArg, Param},
protocol::{PyIter, PyIterReturn, PyNumber},
types::{Callable, Constructor, IterNext, Iterable, SelfIter},
Expand Down Expand Up @@ -244,14 +245,9 @@ mod _csv {
}

#[pyfunction]
fn list_dialects(vm: &VirtualMachine) -> rustpython_vm::builtins::PyListRef {
fn list_dialects(vm: &VirtualMachine) -> PyListOf<String> {
let names = GLOBAL_HASHMAP.lock().keys().cloned().collect_vec();
let t = names
.into_iter()
.map(|x| vm.ctx.new_str(x).into())
.collect_vec();
// .iter().map(|x| vm.ctx.new_str(x.clone()).into_pyobject(vm)).collect_vec();
vm.ctx.new_list(t)
PyListOf::new(names, vm)
}

#[derive(FromArgs)]
Expand Down
118 changes: 118 additions & 0 deletions crates/vm/src/convert/dict.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
use core::{fmt, marker::PhantomData};

use crate::{
PyObjectRef, PyResult, VirtualMachine,
builtins::PyDictRef,
object::{Traverse, TraverseFn},
};

use super::ToPyObject;

/// A Python dict constructed from Rust key/value pairs.
///
/// Keys use Python hashing and equality; later equal keys replace earlier values.
/// Construction can execute Python code and propagates its exceptions. Cloning
/// this handle shares the same dictionary, including subsequent mutations.
///
/// `K` and `V` describe the input conversion, not runtime invariants: Python can
/// insert other types. Access through [`Self::as_dict`] is therefore untyped.
pub struct PyDictOf<K, V> {
dict: PyDictRef,
types: PhantomData<fn() -> (K, V)>,
}

impl<K: ToPyObject, V: ToPyObject> PyDictOf<K, V> {
pub fn try_new(items: impl IntoIterator<Item = (K, V)>, vm: &VirtualMachine) -> PyResult<Self> {
let dict = vm.ctx.new_dict();
for (key, value) in items {
let key = key.to_pyobject(vm);
let value = value.to_pyobject(vm);
dict.set_item(&*key, value, vm)?;
}
Ok(Self {
dict,
types: PhantomData,
})
}
}

impl<K, V> PyDictOf<K, V> {
#[must_use]
pub fn as_dict(&self) -> &PyDictRef {
&self.dict
}

#[must_use]
pub fn into_dict(self) -> PyDictRef {
self.dict
}
}

impl<K, V> Clone for PyDictOf<K, V> {
fn clone(&self) -> Self {
Self {
dict: self.dict.clone(),
types: PhantomData,
}
}
}

impl<K, V> fmt::Debug for PyDictOf<K, V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.dict.fmt(f)
}
}

impl<K, V> ToPyObject for PyDictOf<K, V> {
fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef {
self.dict.into()
}
}

impl<K, V> From<PyDictOf<K, V>> for PyObjectRef {
fn from(value: PyDictOf<K, V>) -> Self {
value.dict.into()
}
}

// SAFETY: Only `dict` owns a Python reference; visit it once without cloning.
unsafe impl<K, V> Traverse for PyDictOf<K, V> {
fn traverse(&self, tracer: &mut TraverseFn<'_>) {
self.dict.traverse(tracer);
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::{AsObject, Interpreter};

#[test]
fn pairs_use_python_key_semantics_and_propagate_errors() {
Interpreter::without_stdlib(Default::default()).enter(|vm| {
let first: PyObjectRef = vm.ctx.new_bool(true).into();
let dict = PyDictOf::try_new([(first.clone(), 10), (vm.ctx.new_int(1).into(), 20)], vm)
.unwrap();
let keys = dict.as_dict().keys_vec();
assert_eq!(keys.len(), 1);
assert!(keys[0].is(&first));
assert_eq!(
dict.as_dict()
.get_item(&*first, vm)
.unwrap()
.try_into_value::<i32>(vm)
.unwrap(),
20
);
assert!(dict.clone().to_pyobject(vm).is(dict.as_dict()));
let mut visits = 0;
dict.traverse(&mut |obj| {
assert!(obj.is(dict.as_dict()));
visits += 1;
});
assert_eq!(visits, 1);
let error = PyDictOf::try_new([(vm.ctx.new_list(vec![]), 1)], vm).unwrap_err();
assert!(error.fast_isinstance(vm.ctx.exceptions.type_error));
});
}
}
134 changes: 134 additions & 0 deletions crates/vm/src/convert/list.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
use core::{fmt, marker::PhantomData};

use crate::{
PyObjectRef, VirtualMachine,
builtins::PyListRef,
object::{Traverse, TraverseFn},
};

use super::ToPyObject;

/// A Python list constructed from Rust values of type `T`.
Comment thread
1ndahous3 marked this conversation as resolved.
///
/// Unlike `Vec<u8>`, which converts to Python `bytes`, `PyListOf<u8>` produces
/// a list of integers. Construction converts each element once; cloning this
/// handle shares the same Python list, including subsequent mutations.
///
/// `T` describes the input conversion, not a runtime invariant: Python can add
/// objects of any type. Access through [`Self::as_list`] is therefore untyped.
pub struct PyListOf<T> {
list: PyListRef,
element: PhantomData<fn() -> T>,
}

impl<T: ToPyObject> PyListOf<T> {
pub fn new(items: impl IntoIterator<Item = T>, vm: &VirtualMachine) -> Self {
Self {
list: vm
.ctx
.new_list(items.into_iter().map(|item| item.to_pyobject(vm)).collect()),
element: PhantomData,
}
}
}

impl<T> PyListOf<T> {
#[must_use]
pub fn as_list(&self) -> &PyListRef {
&self.list
}

#[must_use]
pub fn into_list(self) -> PyListRef {
self.list
}
}

impl<T> Clone for PyListOf<T> {
fn clone(&self) -> Self {
Self {
list: self.list.clone(),
element: PhantomData,
}
}
}

impl<T> fmt::Debug for PyListOf<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.list.fmt(f)
}
}

impl<T> ToPyObject for PyListOf<T> {
fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef {
self.list.into()
}
}

impl<T> From<PyListOf<T>> for PyObjectRef {
fn from(value: PyListOf<T>) -> Self {
value.list.into()
}
}

// SAFETY: Only `list` owns a Python reference; visit it once without cloning.
unsafe impl<T> Traverse for PyListOf<T> {
fn traverse(&self, tracer: &mut TraverseFn<'_>) {
self.list.traverse(tracer);
}
}

#[cfg(test)]
mod tests {
use super::*;
use crate::{AsObject, Interpreter, builtins::PyBytes};

#[test]
fn explicit_list_conversion() {
Interpreter::without_stdlib(Default::default()).enter(|vm| {
let list = PyListOf::new([0_u8, 255].into_iter().filter(|_| true), vm);
assert_eq!(
list.as_list()
.as_object()
.try_to_value::<Vec<u8>>(vm)
.unwrap(),
[0, 255]
);
assert!(
vec![0_u8, 255]
.to_pyobject(vm)
.downcast_ref::<PyBytes>()
.is_some()
);
assert!(
PyListOf::<u8>::new([], vm)
.as_list()
.borrow_vec()
.is_empty()
);
});
}

#[test]
fn shared_identity_and_traversal_do_not_require_element_traits() {
struct Item;
impl ToPyObject for Item {
fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
vm.ctx.new_int(1).into()
}
}
Interpreter::without_stdlib(Default::default()).enter(|vm| {
let list = PyListOf::new([Item], vm);
let copy = list.clone();
list.as_list().borrow_vec_mut().push(vm.ctx.none());
assert_eq!(copy.as_list().borrow_vec().len(), 2);
let mut visits = 0;
copy.traverse(&mut |obj| {
assert!(obj.is(list.as_list()));
visits += 1;
});
assert_eq!(visits, 1);
assert!(copy.to_pyobject(vm).is(&list.into_list()));
});
}
}
6 changes: 6 additions & 0 deletions crates/vm/src/convert/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
mod dict;
mod into_object;
mod list;
mod set;
mod to_pyobject;
mod transmute_from;
mod try_from;

pub use dict::PyDictOf;
pub use into_object::IntoObject;
pub use list::PyListOf;
pub use set::PySetOf;
pub use to_pyobject::{IntoPyException, ToPyException, ToPyObject, ToPyResult};
pub use transmute_from::TransmuteFromObject;
pub use try_from::{TryFromBorrowedObject, TryFromObject};
Loading
Loading