Skip to content

Commit 7f6e016

Browse files
authored
Merge pull request RustPython#3282 from youknowone/remove-ref
Whitelist special-enough types to have PyRef aliases
2 parents 40397a4 + c05e8eb commit 7f6e016

File tree

12 files changed

+65
-64
lines changed

12 files changed

+65
-64
lines changed

stdlib/src/math.rs

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@ pub(crate) use math::make_module;
33
#[pymodule]
44
mod math {
55
use crate::vm::{
6-
builtins::{try_bigint_to_f64, try_f64_to_bigint, PyFloatRef, PyInt, PyIntRef},
6+
builtins::{try_bigint_to_f64, try_f64_to_bigint, PyFloat, PyInt, PyIntRef},
77
function::{ArgIntoFloat, ArgIterable, OptionalArg, PosArgs},
88
utils::Either,
9-
PyObjectRef, PyResult, PySequence, TypeProtocol, VirtualMachine,
9+
PyObjectRef, PyRef, PyResult, PySequence, TypeProtocol, VirtualMachine,
1010
};
1111
use num_bigint::BigInt;
1212
use num_traits::{One, Signed, Zero};
@@ -460,7 +460,11 @@ mod math {
460460
}
461461

462462
#[pyfunction]
463-
fn ldexp(x: Either<PyFloatRef, PyIntRef>, i: PyIntRef, vm: &VirtualMachine) -> PyResult<f64> {
463+
fn ldexp(
464+
x: Either<PyRef<PyFloat>, PyIntRef>,
465+
i: PyIntRef,
466+
vm: &VirtualMachine,
467+
) -> PyResult<f64> {
464468
let value = match x {
465469
Either::A(f) => f.to_f64(),
466470
Either::B(z) => try_bigint_to_f64(z.as_bigint(), vm)?,

stdlib/src/termios.rs

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -67,26 +67,23 @@ mod termios {
6767
termios::cfsetospeed(&mut termios, ospeed.try_into_value(vm)?)
6868
.map_err(|e| termios_error(e, vm))?;
6969
let cc = PyListRef::try_from_object(vm, cc)?;
70-
{
71-
let cc = cc.borrow_vec();
72-
let cc = <&[PyObjectRef; NCCS]>::try_from(&*cc).map_err(|_| {
73-
vm.new_type_error(format!(
74-
"tcsetattr: attributes[6] must be {} element list",
75-
NCCS
76-
))
77-
})?;
78-
for (cc, x) in termios.c_cc.iter_mut().zip(cc.iter()) {
79-
*cc = if let Some(c) = x.payload::<PyBytes>().filter(|b| b.as_bytes().len() == 1) {
80-
c.as_bytes()[0] as _
81-
} else if let Some(i) = x.payload::<PyInt>() {
82-
i.try_to_primitive(vm)?
83-
} else {
84-
return Err(vm.new_type_error(
85-
"tcsetattr: elements of attributes must be characters or integers"
86-
.to_owned(),
87-
));
88-
};
89-
}
70+
let cc = cc.borrow_vec();
71+
let cc = <&[PyObjectRef; NCCS]>::try_from(&*cc).map_err(|_| {
72+
vm.new_type_error(format!(
73+
"tcsetattr: attributes[6] must be {} element list",
74+
NCCS
75+
))
76+
})?;
77+
for (cc, x) in termios.c_cc.iter_mut().zip(cc.iter()) {
78+
*cc = if let Some(c) = x.payload::<PyBytes>().filter(|b| b.as_bytes().len() == 1) {
79+
c.as_bytes()[0] as _
80+
} else if let Some(i) = x.payload::<PyInt>() {
81+
i.try_to_primitive(vm)?
82+
} else {
83+
return Err(vm.new_type_error(
84+
"tcsetattr: elements of attributes must be characters or integers".to_owned(),
85+
));
86+
};
9087
}
9188

9289
termios::tcsetattr(fd, when, &termios).map_err(|e| termios_error(e, vm))?;

vm/src/builtins/float.rs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ macro_rules! impl_try_from_object_float {
9494
($($t:ty),*) => {
9595
$(impl TryFromObject for $t {
9696
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
97-
PyFloatRef::try_from_object(vm, obj).map(|f| f.to_f64() as $t)
97+
PyRef::<PyFloat>::try_from_object(vm, obj).map(|f| f.to_f64() as $t)
9898
}
9999
})*
100100
};
@@ -539,8 +539,6 @@ impl Hashable for PyFloat {
539539
}
540540
}
541541

542-
pub type PyFloatRef = PyRef<PyFloat>;
543-
544542
// Retrieve inner float value:
545543
pub(crate) fn get_value(obj: &PyObjectRef) -> f64 {
546544
obj.payload::<PyFloat>().unwrap().value

vm/src/builtins/list.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::{PositionIterInternal, PyGenericAlias, PySliceRef, PyTupleRef, PyTypeRef};
1+
use super::{PositionIterInternal, PyGenericAlias, PySlice, PyTupleRef, PyTypeRef};
22
use crate::common::lock::{
33
PyMappedRwLockReadGuard, PyMutex, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard,
44
};
@@ -111,7 +111,7 @@ impl PyList {
111111
}
112112

113113
#[pymethod(magic)]
114-
fn add(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyListRef> {
114+
fn add(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
115115
let other = other.payload_if_subclass::<PyList>(vm).ok_or_else(|| {
116116
vm.new_type_error(format!(
117117
"Cannot add {} and {}",
@@ -146,7 +146,7 @@ impl PyList {
146146
}
147147

148148
#[pymethod]
149-
fn copy(&self, vm: &VirtualMachine) -> PyListRef {
149+
fn copy(&self, vm: &VirtualMachine) -> PyRef<Self> {
150150
Self::new_ref(self.borrow_vec().to_vec(), &vm.ctx)
151151
}
152152

@@ -210,7 +210,12 @@ impl PyList {
210210
}
211211
}
212212

213-
fn setslice(&self, slice: PySliceRef, sec: ArgIterable, vm: &VirtualMachine) -> PyResult<()> {
213+
fn setslice(
214+
&self,
215+
slice: PyRef<PySlice>,
216+
sec: ArgIterable,
217+
vm: &VirtualMachine,
218+
) -> PyResult<()> {
214219
let items: Result<Vec<PyObjectRef>, _> = sec.iter(vm)?.collect();
215220
let items = items?;
216221
let slice = slice.to_saturated(vm)?;
@@ -492,7 +497,7 @@ impl PyList {
492497
removed.map(drop)
493498
}
494499

495-
fn delslice(&self, slice: PySliceRef, vm: &VirtualMachine) -> PyResult<()> {
500+
fn delslice(&self, slice: PyRef<PySlice>, vm: &VirtualMachine) -> PyResult<()> {
496501
let slice = slice.to_saturated(vm)?;
497502
self.borrow_vec_mut().delete_slice(vm, slice)
498503
}

vm/src/builtins/memory.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::{PyBytes, PyBytesRef, PyList, PyListRef, PySliceRef, PyStr, PyStrRef, PyTypeRef};
1+
use super::{PyBytes, PyBytesRef, PyList, PyListRef, PySlice, PyStr, PyStrRef, PyTypeRef};
22
use crate::common::{
33
borrow::{BorrowedValue, BorrowedValueMut},
44
hash::PyHash,
@@ -250,7 +250,7 @@ impl PyMemoryView {
250250
})
251251
}
252252

253-
fn getitem_by_slice(zelf: PyRef<Self>, slice: PySliceRef, vm: &VirtualMachine) -> PyResult {
253+
fn getitem_by_slice(zelf: PyRef<Self>, slice: PyRef<PySlice>, vm: &VirtualMachine) -> PyResult {
254254
// slicing a memoryview return a new memoryview
255255
let len = zelf.buffer.options.len;
256256
let (range, step, is_negative_step) =
@@ -368,7 +368,7 @@ impl PyMemoryView {
368368

369369
fn setitem_by_slice(
370370
zelf: PyRef<Self>,
371-
slice: PySliceRef,
371+
slice: PyRef<PySlice>,
372372
items: PyObjectRef,
373373
vm: &VirtualMachine,
374374
) -> PyResult<()> {
@@ -501,7 +501,7 @@ impl PyMemoryView {
501501
}
502502

503503
#[pymethod]
504-
fn tolist(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<PyListRef> {
504+
fn tolist(zelf: PyRef<Self>, vm: &VirtualMachine) -> PyResult<Vec<PyObjectRef>> {
505505
zelf.try_not_released(vm)?;
506506

507507
let bytes = &*zelf.obj_bytes();
@@ -516,7 +516,7 @@ impl PyMemoryView {
516516
})
517517
.try_collect()?;
518518

519-
Ok(PyList::from(elements).into_ref(vm))
519+
Ok(elements)
520520
}
521521

522522
#[pymethod]
@@ -845,7 +845,7 @@ fn format_unpack(
845845
})
846846
}
847847

848-
pub fn unpack_bytes_seq_to_list(
848+
fn unpack_bytes_seq_to_list(
849849
bytes: &[u8],
850850
format: &str,
851851
vm: &VirtualMachine,

vm/src/builtins/mod.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
//! This package contains the python basic/builtin types
2+
//! 7 common PyRef type aliases are exposed - PyBytesRef, PyDictRef, PyIntRef, PyListRef, PyStrRef, PyTypeRef, PyTupleRef
3+
//! Do not add more PyRef type aliases. They will be rare enough to use directly PyRef<T>.
24
35
pub(crate) mod asyncgenerator;
46
pub use asyncgenerator::PyAsyncGen;
@@ -22,7 +24,7 @@ pub use enumerate::PyEnumerate;
2224
pub(crate) mod filter;
2325
pub use filter::PyFilter;
2426
pub(crate) mod float;
25-
pub use float::{PyFloat, PyFloatRef};
27+
pub use float::PyFloat;
2628
pub(crate) mod frame;
2729
pub(crate) mod function;
2830
pub use function::{PyBoundMethod, PyFunction};
@@ -67,7 +69,7 @@ pub use set::{PyFrozenSet, PySet};
6769
pub(crate) mod singletons;
6870
pub use singletons::{PyNone, PyNotImplemented};
6971
pub(crate) mod slice;
70-
pub use slice::{PyEllipsis, PySlice, PySliceRef};
72+
pub use slice::{PyEllipsis, PySlice};
7173
pub(crate) mod staticmethod;
7274
pub use staticmethod::PyStaticMethod;
7375
pub(crate) mod traceback;

vm/src/builtins/range.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use super::{PyInt, PyIntRef, PySlice, PySliceRef, PyTupleRef, PyTypeRef};
1+
use super::{PyInt, PyIntRef, PySlice, PyTupleRef, PyTypeRef};
22
use crate::builtins::builtins_iter;
33
use crate::common::hash::PyHash;
44
use crate::{
@@ -664,7 +664,7 @@ fn range_state(length: &BigInt, state: PyObjectRef, vm: &VirtualMachine) -> PyRe
664664

665665
pub enum RangeIndex {
666666
Int(PyIntRef),
667-
Slice(PySliceRef),
667+
Slice(PyRef<PySlice>),
668668
}
669669

670670
impl TryFromObject for RangeIndex {

vm/src/builtins/slice.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@ impl PyValue for PySlice {
2424
}
2525
}
2626

27-
pub type PySliceRef = PyRef<PySlice>;
28-
2927
#[pyimpl(with(Hashable, Comparable))]
3028
impl PySlice {
3129
#[pyproperty]

vm/src/sliceable.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@ use std::ops::Range;
33

44
use crate::builtins::int::PyInt;
55
// export through slicable module, not slice.
6+
use crate::builtins::slice::PySlice;
67
pub use crate::builtins::slice::{saturate_index, SaturatedSlice};
7-
use crate::builtins::slice::{PySlice, PySliceRef};
88
use crate::utils::Either;
99
use crate::VirtualMachine;
10-
use crate::{PyObjectRef, PyResult, TypeProtocol};
10+
use crate::{PyObjectRef, PyRef, PyResult, TypeProtocol};
1111

1212
pub trait PySliceableSequenceMut {
1313
type Item: Clone;
@@ -332,7 +332,7 @@ impl<T: Clone> PySliceableSequence for [T] {
332332

333333
pub enum SequenceIndex {
334334
Int(isize),
335-
Slice(PySliceRef),
335+
Slice(PyRef<PySlice>),
336336
}
337337

338338
impl SequenceIndex {

vm/src/stdlib/sre.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,7 @@ pub(crate) use _sre::make_module;
44
mod _sre {
55
use crate::{
66
builtins::{
7-
PyCallableIterator, PyDictRef, PyInt, PyList, PyListRef, PyStr, PyStrRef, PyTuple,
8-
PyTupleRef,
7+
PyCallableIterator, PyDictRef, PyInt, PyList, PyStr, PyStrRef, PyTuple, PyTupleRef,
98
},
109
common::{ascii, hash::PyHash},
1110
function::{ArgCallable, IntoPyObject, OptionalArg, PosArgs},
@@ -247,7 +246,7 @@ mod _sre {
247246
zelf: PyRef<Pattern>,
248247
string_args: StringArgs,
249248
vm: &VirtualMachine,
250-
) -> PyResult<PyListRef> {
249+
) -> PyResult<Vec<PyObjectRef>> {
251250
zelf.with_state(
252251
string_args.string.clone(),
253252
string_args.pos,
@@ -277,7 +276,7 @@ mod _sre {
277276
state.start = state.string_position;
278277
state.reset();
279278
}
280-
Ok(PyList::from(matchlist).into_ref(vm))
279+
Ok(matchlist)
281280
},
282281
)
283282
}
@@ -332,7 +331,7 @@ mod _sre {
332331
zelf: PyRef<Pattern>,
333332
split_args: SplitArgs,
334333
vm: &VirtualMachine,
335-
) -> PyResult<PyListRef> {
334+
) -> PyResult<Vec<PyObjectRef>> {
336335
zelf.with_state(split_args.string.clone(), 0, usize::MAX, vm, |mut state| {
337336
let mut splitlist: Vec<PyObjectRef> = Vec::new();
338337

@@ -367,7 +366,7 @@ mod _sre {
367366
// get segment following last match (even if empty)
368367
splitlist.push(slice_drive(&state.string, last, state.string.count(), vm));
369368

370-
Ok(PyList::from(splitlist).into_ref(vm))
369+
Ok(splitlist)
371370
})
372371
}
373372

vm/src/stdlib/sys.rs

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ mod sys {
1111
hash::{PyHash, PyUHash},
1212
};
1313
use crate::{
14-
builtins::{PyDictRef, PyListRef, PyNamespace, PyStr, PyStrRef, PyTupleRef, PyTypeRef},
14+
builtins::{PyDictRef, PyNamespace, PyStr, PyStrRef, PyTupleRef, PyTypeRef},
1515
frame::FrameRef,
1616
function::{FuncArgs, OptionalArg, PosArgs},
1717
stdlib::builtins,
@@ -99,15 +99,13 @@ mod sys {
9999
// alphabetical order with segments of pyattr and others
100100

101101
#[pyattr]
102-
fn argv(vm: &VirtualMachine) -> PyListRef {
103-
vm.ctx.new_list(
104-
vm.state
105-
.settings
106-
.argv
107-
.iter()
108-
.map(|arg| vm.ctx.new_str(arg.clone()).into())
109-
.collect(),
110-
)
102+
fn argv(vm: &VirtualMachine) -> Vec<PyObjectRef> {
103+
vm.state
104+
.settings
105+
.argv
106+
.iter()
107+
.map(|arg| vm.ctx.new_str(arg.clone()).into())
108+
.collect()
111109
}
112110

113111
#[pyattr]

wasm/lib/src/js_module.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::{
55
};
66
use js_sys::{Array, Object, Promise, Reflect};
77
use rustpython_vm::{
8-
builtins::{PyBaseExceptionRef, PyFloatRef, PyStrRef, PyType, PyTypeRef},
8+
builtins::{PyBaseExceptionRef, PyFloat, PyStrRef, PyType, PyTypeRef},
99
function::{ArgCallable, IntoPyObject, OptionalArg, OptionalOption, PosArgs},
1010
protocol::PyIterReturn,
1111
types::{IterNext, IterNextIterable},
@@ -110,7 +110,7 @@ impl PyJsValue {
110110
}
111111

112112
#[pymethod]
113-
fn new_from_float(&self, n: PyFloatRef) -> PyJsValue {
113+
fn new_from_float(&self, n: PyRef<PyFloat>) -> PyJsValue {
114114
PyJsValue::new(n.to_f64())
115115
}
116116

0 commit comments

Comments
 (0)