Skip to content

Commit 3fd0382

Browse files
coolreader18youknowone
authored andcommitted
Use RPITIT where applicable
1 parent 3e98e5e commit 3fd0382

10 files changed

Lines changed: 70 additions & 84 deletions

File tree

‎vm/src/anystr.rs‎

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -150,20 +150,14 @@ where
150150
pub trait AnyStr {
151151
type Char: Copy;
152152
type Container: AnyStrContainer<Self> + Extend<Self::Char>;
153-
type CharIter<'a>: Iterator<Item = char> + 'a
154-
where
155-
Self: 'a;
156-
type ElementIter<'a>: Iterator<Item = Self::Char> + 'a
157-
where
158-
Self: 'a;
159153

160154
fn element_bytes_len(c: Self::Char) -> usize;
161155

162156
fn to_container(&self) -> Self::Container;
163157
fn as_bytes(&self) -> &[u8];
164158
fn as_utf8_str(&self) -> Result<&str, std::str::Utf8Error>;
165-
fn chars(&self) -> Self::CharIter<'_>;
166-
fn elements(&self) -> Self::ElementIter<'_>;
159+
fn chars(&self) -> impl Iterator<Item = char>;
160+
fn elements(&self) -> impl Iterator<Item = Self::Char>;
167161
fn get_bytes(&self, range: std::ops::Range<usize>) -> &Self;
168162
// FIXME: get_chars is expensive for str
169163
fn get_chars(&self, range: std::ops::Range<usize>) -> &Self;

‎vm/src/builtins/builtin_func.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ impl PyNativeFunction {
4949
)
5050
}
5151

52-
pub fn as_func(&self) -> &'static PyNativeFn {
52+
pub fn as_func(&self) -> &'static dyn PyNativeFn {
5353
self.value.func
5454
}
5555
}

‎vm/src/builtins/list.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -358,13 +358,13 @@ where
358358
}
359359

360360
impl MutObjectSequenceOp for PyList {
361-
type Guard<'a> = PyMappedRwLockReadGuard<'a, [PyObjectRef]>;
361+
type Inner = [PyObjectRef];
362362

363-
fn do_get<'a>(index: usize, guard: &'a Self::Guard<'_>) -> Option<&'a PyObjectRef> {
364-
guard.get(index)
363+
fn do_get(index: usize, inner: &[PyObjectRef]) -> Option<&PyObjectRef> {
364+
inner.get(index)
365365
}
366366

367-
fn do_lock(&self) -> Self::Guard<'_> {
367+
fn do_lock(&self) -> impl std::ops::Deref<Target = [PyObjectRef]> {
368368
self.borrow_vec()
369369
}
370370
}

‎vm/src/builtins/str.rs‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1692,8 +1692,6 @@ impl AnyStrContainer<str> for String {
16921692
impl AnyStr for str {
16931693
type Char = char;
16941694
type Container = String;
1695-
type CharIter<'a> = std::str::Chars<'a>;
1696-
type ElementIter<'a> = std::str::Chars<'a>;
16971695

16981696
fn element_bytes_len(c: char) -> usize {
16991697
c.len_utf8()
@@ -1711,11 +1709,11 @@ impl AnyStr for str {
17111709
Ok(self)
17121710
}
17131711

1714-
fn chars(&self) -> Self::CharIter<'_> {
1712+
fn chars(&self) -> impl Iterator<Item = char> {
17151713
str::chars(self)
17161714
}
17171715

1718-
fn elements(&self) -> Self::ElementIter<'_> {
1716+
fn elements(&self) -> impl Iterator<Item = char> {
17191717
str::chars(self)
17201718
}
17211719

‎vm/src/bytesinner.rs‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1024,8 +1024,6 @@ const ASCII_WHITESPACES: [u8; 6] = [0x20, 0x09, 0x0a, 0x0c, 0x0d, 0x0b];
10241024
impl AnyStr for [u8] {
10251025
type Char = u8;
10261026
type Container = Vec<u8>;
1027-
type CharIter<'a> = bstr::Chars<'a>;
1028-
type ElementIter<'a> = std::iter::Copied<std::slice::Iter<'a, u8>>;
10291027

10301028
fn element_bytes_len(_: u8) -> usize {
10311029
1
@@ -1043,11 +1041,11 @@ impl AnyStr for [u8] {
10431041
std::str::from_utf8(self)
10441042
}
10451043

1046-
fn chars(&self) -> Self::CharIter<'_> {
1044+
fn chars(&self) -> impl Iterator<Item = char> {
10471045
bstr::ByteSlice::chars(self)
10481046
}
10491047

1050-
fn elements(&self) -> Self::ElementIter<'_> {
1048+
fn elements(&self) -> impl Iterator<Item = u8> {
10511049
self.iter().copied()
10521050
}
10531051

‎vm/src/function/builtin.rs‎

Lines changed: 42 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,14 @@ use std::marker::PhantomData;
77

88
/// A built-in Python function.
99
// PyCFunction in CPython
10-
pub type PyNativeFn = py_dyn_fn!(dyn Fn(&VirtualMachine, FuncArgs) -> PyResult);
10+
pub trait PyNativeFn:
11+
Fn(&VirtualMachine, FuncArgs) -> PyResult + PyThreadingConstraint + 'static
12+
{
13+
}
14+
impl<F: Fn(&VirtualMachine, FuncArgs) -> PyResult + PyThreadingConstraint + 'static> PyNativeFn
15+
for F
16+
{
17+
}
1118

1219
/// Implemented by types that are or can generate built-in functions.
1320
///
@@ -34,40 +41,44 @@ pub trait IntoPyNativeFn<Kind>: Sized + PyThreadingConstraint + 'static {
3441
/// `IntoPyNativeFn::into_func()` generates a PyNativeFn that performs the
3542
/// appropriate type and arity checking, any requested conversions, and then if
3643
/// successful calls the function with the extracted parameters.
37-
fn into_func(self) -> &'static PyNativeFn {
38-
let boxed = Box::new(move |vm: &VirtualMachine, args| self.call(vm, args));
39-
Box::leak(boxed)
44+
fn into_func(self) -> impl PyNativeFn {
45+
into_func(self)
4046
}
47+
}
4148

42-
/// Equivalent to `into_func()`, but accessible as a constant. This is only
43-
/// valid if this function is zero-sized, i.e. that
44-
/// `std::mem::size_of::<F>() == 0`. If it isn't, use of this constant will
45-
/// raise a compile error.
46-
const STATIC_FUNC: &'static PyNativeFn = {
47-
if std::mem::size_of::<Self>() == 0 {
48-
&|vm, args| {
49-
// SAFETY: we just confirmed that Self is zero-sized, so there
50-
// aren't any bytes in it that could be uninit.
51-
#[allow(clippy::uninit_assumed_init)]
52-
let f = unsafe { std::mem::MaybeUninit::<Self>::uninit().assume_init() };
53-
f.call(vm, args)
49+
const fn into_func<F: IntoPyNativeFn<Kind>, Kind>(f: F) -> impl PyNativeFn {
50+
move |vm: &VirtualMachine, args| f.call(vm, args)
51+
}
52+
53+
const fn zst_ref_out_of_thin_air<T: 'static>(x: T) -> &'static T {
54+
// if T is zero-sized, there's no issue forgetting it - even if it does have a Drop impl, it
55+
// would never get called anyway if we consider this semantically a Box::leak(Box::new(x))-type
56+
// operation. if T isn't zero-sized, we don't have to worry about it because we'll fail to compile.
57+
std::mem::forget(x);
58+
trait Zst: Sized + 'static {
59+
const THIN_AIR: &'static Self = {
60+
if std::mem::size_of::<Self>() == 0 {
61+
// SAFETY: we just confirmed that Self is zero-sized, so we can
62+
// pull a value of it out of thin air.
63+
unsafe { std::ptr::NonNull::<Self>::dangling().as_ref() }
64+
} else {
65+
panic!("can't use a non-zero-sized type here")
5466
}
55-
} else {
56-
panic!("function must be zero-sized to access STATIC_FUNC")
57-
}
58-
};
67+
};
68+
}
69+
impl<T: 'static> Zst for T {}
70+
<T as Zst>::THIN_AIR
5971
}
6072

6173
/// Get the [`STATIC_FUNC`](IntoPyNativeFn::STATIC_FUNC) of the passed function. The same
6274
/// requirements of zero-sizedness apply, see that documentation for details.
75+
///
76+
/// Equivalent to [`IntoPyNativeFn::into_func()`], but usable in a const context. This is only
77+
/// valid if the function is zero-sized, i.e. that `std::mem::size_of::<F>() == 0`. If you call
78+
/// this function with a non-zero-sized function, it will raise a compile error.
6379
#[inline(always)]
64-
pub const fn static_func<Kind, F: IntoPyNativeFn<Kind>>(f: F) -> &'static PyNativeFn {
65-
// if f is zero-sized, there's no issue forgetting it - even if a capture of f does have a Drop
66-
// impl, it would never get called anyway. If you passed it to into_func, it would just get
67-
// Box::leak'd, and as a 'static reference it'll never be dropped. and if f isn't zero-sized,
68-
// we'll never reach this point anyway because we'll fail to compile.
69-
std::mem::forget(f);
70-
F::STATIC_FUNC
80+
pub const fn static_func<Kind, F: IntoPyNativeFn<Kind>>(f: F) -> &'static dyn PyNativeFn {
81+
zst_ref_out_of_thin_air(into_func(f))
7182
}
7283

7384
// TODO: once higher-rank trait bounds are stabilized, remove the `Kind` type
@@ -207,16 +218,16 @@ into_py_native_fn_tuple!(
207218
#[cfg(test)]
208219
mod tests {
209220
use super::*;
221+
use std::mem::size_of_val;
210222

211223
#[test]
212224
fn test_into_native_fn_noalloc() {
213-
let check_zst = |f: &'static PyNativeFn| assert_eq!(std::mem::size_of_val(f), 0);
214225
fn py_func(_b: bool, _vm: &crate::VirtualMachine) -> i32 {
215226
1
216227
}
217-
check_zst(py_func.into_func());
228+
assert_eq!(size_of_val(&py_func.into_func()), 0);
218229
let empty_closure = || "foo".to_owned();
219-
check_zst(empty_closure.into_func());
220-
check_zst(static_func(empty_closure));
230+
assert_eq!(size_of_val(&empty_closure.into_func()), 0);
231+
assert_eq!(size_of_val(static_func(empty_closure)), 0);
221232
}
222233
}

‎vm/src/function/method.rs‎

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ macro_rules! define_methods {
5656
($($name:literal => $func:ident as $flags:ident),+) => {
5757
vec![ $( $crate::function::PyMethodDef {
5858
name: $name,
59-
func: $crate::function::IntoPyNativeFn::into_func($func),
59+
func: $crate::function::static_func($func),
6060
flags: $crate::function::PyMethodFlags::$flags,
6161
doc: None,
6262
}),+ ]
@@ -66,27 +66,12 @@ macro_rules! define_methods {
6666
#[derive(Clone)]
6767
pub struct PyMethodDef {
6868
pub name: &'static str, // TODO: interned
69-
pub func: &'static PyNativeFn,
69+
pub func: &'static dyn PyNativeFn,
7070
pub flags: PyMethodFlags,
7171
pub doc: Option<&'static str>, // TODO: interned
7272
}
7373

7474
impl PyMethodDef {
75-
#[inline]
76-
pub fn new<Kind>(
77-
name: &'static str,
78-
func: impl IntoPyNativeFn<Kind>,
79-
flags: PyMethodFlags,
80-
doc: Option<&'static str>,
81-
) -> Self {
82-
Self {
83-
name,
84-
func: func.into_func(),
85-
flags,
86-
doc,
87-
}
88-
}
89-
9075
#[inline]
9176
pub const fn new_const<Kind>(
9277
name: &'static str,

‎vm/src/sequence.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@ use crate::{
33
vm::VirtualMachine, AsObject, PyObject, PyObjectRef, PyResult,
44
};
55
use optional::Optioned;
6-
use std::ops::Range;
6+
use std::ops::{Deref, Range};
77

88
pub trait MutObjectSequenceOp {
9-
type Guard<'a>: 'a;
9+
type Inner: ?Sized;
1010

11-
fn do_get<'a>(index: usize, guard: &'a Self::Guard<'_>) -> Option<&'a PyObjectRef>;
12-
fn do_lock(&self) -> Self::Guard<'_>;
11+
fn do_get(index: usize, inner: &Self::Inner) -> Option<&PyObjectRef>;
12+
fn do_lock(&self) -> impl Deref<Target = Self::Inner>;
1313

1414
fn mut_count(&self, vm: &VirtualMachine, needle: &PyObject) -> PyResult<usize> {
1515
let mut count = 0;

‎vm/src/stdlib/collections.rs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -416,13 +416,13 @@ mod _collections {
416416
}
417417

418418
impl MutObjectSequenceOp for PyDeque {
419-
type Guard<'a> = PyRwLockReadGuard<'a, VecDeque<PyObjectRef>>;
419+
type Inner = VecDeque<PyObjectRef>;
420420

421-
fn do_get<'a>(index: usize, guard: &'a Self::Guard<'_>) -> Option<&'a PyObjectRef> {
422-
guard.get(index)
421+
fn do_get(index: usize, inner: &Self::Inner) -> Option<&PyObjectRef> {
422+
inner.get(index)
423423
}
424424

425-
fn do_lock(&self) -> Self::Guard<'_> {
425+
fn do_lock(&self) -> impl std::ops::Deref<Target = Self::Inner> {
426426
self.borrow_deque()
427427
}
428428
}

‎vm/src/vm/context.rs‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -291,12 +291,12 @@ impl Context {
291291
let string_pool = StringPool::default();
292292
let names = unsafe { ConstName::new(&string_pool, &types.str_type.to_owned()) };
293293

294-
let slot_new_wrapper = PyMethodDef {
295-
name: names.__new__.as_str(),
296-
func: PyType::__new__.into_func(),
297-
flags: PyMethodFlags::METHOD,
298-
doc: None,
299-
};
294+
let slot_new_wrapper = PyMethodDef::new_const(
295+
names.__new__.as_str(),
296+
PyType::__new__,
297+
PyMethodFlags::METHOD,
298+
None,
299+
);
300300

301301
let empty_str = unsafe { string_pool.intern("", types.str_type.to_owned()) };
302302
let empty_bytes = create_object(PyBytes::from(Vec::new()), types.bytes_type);
@@ -499,7 +499,7 @@ impl Context {
499499
{
500500
let def = PyMethodDef {
501501
name,
502-
func: f.into_func(),
502+
func: Box::leak(Box::new(f.into_func())),
503503
flags,
504504
doc,
505505
};

0 commit comments

Comments
 (0)