Skip to content

Commit c529c24

Browse files
authored
PyRef::into_ref() (#3744)
1 parent 49422c5 commit c529c24

File tree

11 files changed

+55
-49
lines changed

11 files changed

+55
-49
lines changed

examples/call_between_rust_and_python.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ pub fn main() {
3131
#[pymodule]
3232
mod rust_py_module {
3333
use super::*;
34-
use rustpython::vm::{PyObjectRef, builtins::PyList, convert::ToPyObject};
34+
use rustpython::vm::{PyObjectRef, convert::ToPyObject};
3535

3636
#[pyfunction]
3737
fn rust_function(
@@ -58,7 +58,7 @@ python_person.name: {}",
5858
impl ToPyObject for NumVec {
5959
fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
6060
let list = self.0.into_iter().map(|e| vm.new_pyobj(e)).collect();
61-
PyList::new_ref(list, vm.as_ref()).to_pyobject(vm)
61+
vm.ctx.new_list(list).to_pyobject(vm)
6262
}
6363
}
6464

vm/src/builtins/bytearray.rs

Lines changed: 14 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ impl PyByteArray {
134134
SequenceIndex::Slice(slice) => self
135135
.borrow_buf()
136136
.getitem_by_slice(vm, slice)
137-
.map(|x| Self::new_ref(x, &vm.ctx).into()),
137+
.map(|x| vm.ctx.new_bytearray(x).into()),
138138
}
139139
}
140140

@@ -463,11 +463,8 @@ impl PyByteArray {
463463
options: ByteInnerSplitOptions,
464464
vm: &VirtualMachine,
465465
) -> PyResult<Vec<PyObjectRef>> {
466-
self.inner().split(
467-
options,
468-
|s, vm| Self::new_ref(s.to_vec(), &vm.ctx).into(),
469-
vm,
470-
)
466+
self.inner()
467+
.split(options, |s, vm| vm.ctx.new_bytearray(s.to_vec()).into(), vm)
471468
}
472469

473470
#[pymethod]
@@ -476,11 +473,8 @@ impl PyByteArray {
476473
options: ByteInnerSplitOptions,
477474
vm: &VirtualMachine,
478475
) -> PyResult<Vec<PyObjectRef>> {
479-
self.inner().rsplit(
480-
options,
481-
|s, vm| Self::new_ref(s.to_vec(), &vm.ctx).into(),
482-
vm,
483-
)
476+
self.inner()
477+
.rsplit(options, |s, vm| vm.ctx.new_bytearray(s.to_vec()).into(), vm)
484478
}
485479

486480
#[pymethod]
@@ -490,9 +484,10 @@ impl PyByteArray {
490484
let value = self.inner();
491485
let (front, has_mid, back) = value.partition(&sep, vm)?;
492486
Ok(vm.new_tuple((
493-
Self::new_ref(front.to_vec(), &vm.ctx),
494-
Self::new_ref(if has_mid { sep.elements } else { Vec::new() }, &vm.ctx),
495-
Self::new_ref(back.to_vec(), &vm.ctx),
487+
vm.ctx.new_bytearray(front.to_vec()),
488+
vm.ctx
489+
.new_bytearray(if has_mid { sep.elements } else { Vec::new() }),
490+
vm.ctx.new_bytearray(back.to_vec()),
496491
)))
497492
}
498493

@@ -501,9 +496,10 @@ impl PyByteArray {
501496
let value = self.inner();
502497
let (back, has_mid, front) = value.rpartition(&sep, vm)?;
503498
Ok(vm.new_tuple((
504-
Self::new_ref(front.to_vec(), &vm.ctx),
505-
Self::new_ref(if has_mid { sep.elements } else { Vec::new() }, &vm.ctx),
506-
Self::new_ref(back.to_vec(), &vm.ctx),
499+
vm.ctx.new_bytearray(front.to_vec()),
500+
vm.ctx
501+
.new_bytearray(if has_mid { sep.elements } else { Vec::new() }),
502+
vm.ctx.new_bytearray(back.to_vec()),
507503
)))
508504
}
509505

@@ -515,7 +511,7 @@ impl PyByteArray {
515511
#[pymethod]
516512
fn splitlines(&self, options: anystr::SplitLinesArgs, vm: &VirtualMachine) -> Vec<PyObjectRef> {
517513
self.inner()
518-
.splitlines(options, |x| Self::new_ref(x.to_vec(), &vm.ctx).into())
514+
.splitlines(options, |x| vm.ctx.new_bytearray(x.to_vec()).into())
519515
}
520516

521517
#[pymethod]
@@ -878,10 +874,6 @@ impl Representable for PyByteArray {
878874
}
879875
}
880876

881-
// fn set_value(obj: &PyObject, value: Vec<u8>) {
882-
// obj.borrow_mut().kind = PyObjectPayload::Bytes { value };
883-
// }
884-
885877
#[pyclass(module = false, name = "bytearray_iterator")]
886878
#[derive(Debug)]
887879
pub struct PyByteArrayIterator {

vm/src/builtins/classmethod.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,9 @@ impl GetDescriptor for PyClassMethod {
5858
let cls = cls.unwrap_or_else(|| _obj.class().to_owned().into());
5959
let call_descr_get: PyResult<PyObjectRef> = zelf.callable.lock().get_attr("__get__", vm);
6060
match call_descr_get {
61-
Err(_) => Ok(PyBoundMethod::new_ref(cls, zelf.callable.lock().clone(), &vm.ctx).into()),
61+
Err(_) => Ok(PyBoundMethod::new(cls, zelf.callable.lock().clone())
62+
.into_ref(&vm.ctx)
63+
.into()),
6264
Ok(call_descr_get) => call_descr_get.call((cls.clone(), cls), vm),
6365
}
6466
}

vm/src/builtins/complex.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ impl PyPayload for PyComplex {
4242

4343
impl ToPyObject for Complex64 {
4444
fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
45-
PyComplex::new_ref(self, &vm.ctx).into()
45+
PyComplex::from(self).to_pyobject(vm)
4646
}
4747
}
4848

vm/src/builtins/dict.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ impl fmt::Debug for PyDict {
4444
}
4545

4646
impl PyPayload for PyDict {
47+
#[inline]
4748
fn class(ctx: &Context) -> &'static Py<PyType> {
4849
ctx.types.dict_type
4950
}

vm/src/builtins/function.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -554,7 +554,7 @@ impl GetDescriptor for PyFunction {
554554
let obj = if vm.is_none(&obj) && !Self::_cls_is(&cls, obj.class()) {
555555
zelf
556556
} else {
557-
PyBoundMethod::new_ref(obj, zelf, &vm.ctx).into()
557+
PyBoundMethod::new(obj, zelf).into_ref(&vm.ctx).into()
558558
};
559559
Ok(obj)
560560
}
@@ -722,7 +722,7 @@ impl Constructor for PyBoundMethod {
722722
}
723723

724724
impl PyBoundMethod {
725-
fn new(object: PyObjectRef, function: PyObjectRef) -> Self {
725+
pub fn new(object: PyObjectRef, function: PyObjectRef) -> Self {
726726
PyBoundMethod { object, function }
727727
}
728728

vm/src/builtins/list.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ impl PyPayload for PyList {
5858

5959
impl ToPyObject for Vec<PyObjectRef> {
6060
fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
61-
PyList::new_ref(self, &vm.ctx).into()
61+
PyList::from(self).into_ref(&vm.ctx).into()
6262
}
6363
}
6464

@@ -78,7 +78,7 @@ impl PyList {
7878
fn repeat(&self, n: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
7979
let elements = &*self.borrow_vec();
8080
let v = elements.mul(vm, n)?;
81-
Ok(Self::new_ref(v, &vm.ctx))
81+
Ok(Self::from(v).into_ref(&vm.ctx))
8282
}
8383

8484
fn irepeat(zelf: PyRef<Self>, n: isize, vm: &VirtualMachine) -> PyResult<PyRef<Self>> {
@@ -140,7 +140,7 @@ impl PyList {
140140
})?;
141141
let mut elements = self.borrow_vec().to_vec();
142142
elements.extend(other.borrow_vec().iter().cloned());
143-
Ok(Self::new_ref(elements, &vm.ctx))
143+
Ok(Self::from(elements).into_ref(&vm.ctx))
144144
}
145145

146146
#[pymethod]
@@ -176,7 +176,7 @@ impl PyList {
176176

177177
#[pymethod]
178178
fn copy(&self, vm: &VirtualMachine) -> PyRef<Self> {
179-
Self::new_ref(self.borrow_vec().to_vec(), &vm.ctx)
179+
Self::from(self.borrow_vec().to_vec()).into_ref(&vm.ctx)
180180
}
181181

182182
#[allow(clippy::len_without_is_empty)]

vm/src/bytes_inner.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ impl ByteInnerNewOptions {
9696
(OptionalArg::Present(obj), OptionalArg::Missing, OptionalArg::Missing) => {
9797
let obj = obj.clone();
9898
// construct an exact bytes from an exact bytes do not clone
99-
let obj = if cls.is(PyBytes::class(&vm.ctx)) {
99+
let obj = if cls.is(vm.ctx.types.bytes_type) {
100100
match obj.downcast_exact::<PyBytes>(vm) {
101101
Ok(b) => return Ok(b.into_pyref()),
102102
Err(obj) => obj,
@@ -109,7 +109,7 @@ impl ByteInnerNewOptions {
109109
// construct an exact bytes from __bytes__ slot.
110110
// if __bytes__ return a bytes, use the bytes object except we are the subclass of the bytes
111111
let bytes = bytes_method?.call((), vm)?;
112-
let bytes = if cls.is(PyBytes::class(&vm.ctx)) {
112+
let bytes = if cls.is(vm.ctx.types.bytes_type) {
113113
match bytes.downcast::<PyBytes>() {
114114
Ok(b) => return Ok(b),
115115
Err(bytes) => bytes,

vm/src/class.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,16 +13,23 @@ use rustpython_common::static_cell;
1313
pub trait StaticType {
1414
// Ideally, saving PyType is better than PyTypeRef
1515
fn static_cell() -> &'static static_cell::StaticCell<PyTypeRef>;
16+
#[inline]
1617
fn static_metaclass() -> &'static Py<PyType> {
1718
PyType::static_type()
1819
}
20+
#[inline]
1921
fn static_baseclass() -> &'static Py<PyType> {
2022
PyBaseObject::static_type()
2123
}
24+
#[inline]
2225
fn static_type() -> &'static Py<PyType> {
23-
Self::static_cell()
24-
.get()
25-
.expect("static type has not been initialized. e.g. the native types defined in different module may be used before importing library.")
26+
#[cold]
27+
fn fail() -> ! {
28+
panic!(
29+
"static type has not been initialized. e.g. the native types defined in different module may be used before importing library."
30+
);
31+
}
32+
Self::static_cell().get().unwrap_or_else(|| fail())
2633
}
2734
fn init_manually(typ: PyTypeRef) -> &'static Py<PyType> {
2835
let cell = Self::static_cell();

vm/src/vm/context.rs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
use crate::{
22
PyResult, VirtualMachine,
33
builtins::{
4-
PyBaseException, PyBytes, PyComplex, PyDict, PyDictRef, PyEllipsis, PyFloat, PyFrozenSet,
5-
PyInt, PyIntRef, PyList, PyListRef, PyNone, PyNotImplemented, PyStr, PyStrInterned,
6-
PyTuple, PyTupleRef, PyType, PyTypeRef, bytes,
4+
PyBaseException, PyByteArray, PyBytes, PyComplex, PyDict, PyDictRef, PyEllipsis, PyFloat,
5+
PyFrozenSet, PyInt, PyIntRef, PyList, PyListRef, PyNone, PyNotImplemented, PyStr,
6+
PyStrInterned, PyTuple, PyTupleRef, PyType, PyTypeRef,
77
code::{self, PyCode},
88
descriptor::{
99
MemberGetter, MemberKind, MemberSetter, MemberSetterFunc, PyDescriptorOwned,
@@ -418,7 +418,7 @@ impl Context {
418418

419419
#[inline]
420420
pub fn new_str(&self, s: impl Into<pystr::PyStr>) -> PyRef<PyStr> {
421-
pystr::PyStr::new_ref(s, self)
421+
s.into().into_ref(self)
422422
}
423423

424424
pub fn interned_or_new_str<S, M>(&self, s: S) -> PyRef<PyStr>
@@ -433,8 +433,13 @@ impl Context {
433433
}
434434

435435
#[inline]
436-
pub fn new_bytes(&self, data: Vec<u8>) -> PyRef<bytes::PyBytes> {
437-
bytes::PyBytes::new_ref(data, self)
436+
pub fn new_bytes(&self, data: Vec<u8>) -> PyRef<PyBytes> {
437+
PyBytes::from(data).into_ref(self)
438+
}
439+
440+
#[inline]
441+
pub fn new_bytearray(&self, data: Vec<u8>) -> PyRef<PyByteArray> {
442+
PyByteArray::from(data).into_ref(self)
438443
}
439444

440445
#[inline(always)]
@@ -454,12 +459,12 @@ impl Context {
454459

455460
#[inline(always)]
456461
pub fn new_list(&self, elements: Vec<PyObjectRef>) -> PyListRef {
457-
PyList::new_ref(elements, self)
462+
PyList::from(elements).into_ref(self)
458463
}
459464

460465
#[inline(always)]
461466
pub fn new_dict(&self) -> PyDictRef {
462-
PyDict::new_ref(self)
467+
PyDict::default().into_ref(self)
463468
}
464469

465470
pub fn new_class(

0 commit comments

Comments
 (0)