Skip to content

Commit 7d6b36a

Browse files
authored
Merge pull request RustPython#3273 from youknowone/into-pystrref
migrate TryIntoRef to IntoPyStrRef
2 parents e97ad7d + d635a67 commit 7d6b36a

File tree

8 files changed

+67
-77
lines changed

8 files changed

+67
-77
lines changed

vm/src/builtins/pystr.rs

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use crate::{
1616
stdlib::sys,
1717
utils::Either,
1818
IdProtocol, ItemProtocol, PyClassDef, PyClassImpl, PyComparisonValue, PyContext, PyObjectRef,
19-
PyRef, PyResult, PyValue, TryIntoRef, TypeProtocol, VirtualMachine,
19+
PyRef, PyResult, PyValue, TypeProtocol, VirtualMachine,
2020
};
2121
use ascii::{AsciiStr, AsciiString};
2222
use bstr::ByteSlice;
@@ -169,24 +169,42 @@ impl fmt::Display for PyStr {
169169
}
170170
}
171171

172-
impl TryIntoRef<PyStr> for AsciiString {
172+
pub trait IntoPyStrRef {
173+
fn into_pystr_ref(self, vm: &VirtualMachine) -> PyStrRef;
174+
}
175+
176+
impl IntoPyStrRef for PyStrRef {
177+
#[inline]
178+
fn into_pystr_ref(self, _vm: &VirtualMachine) -> PyRef<PyStr> {
179+
self
180+
}
181+
}
182+
183+
impl IntoPyStrRef for PyStr {
184+
#[inline]
185+
fn into_pystr_ref(self, vm: &VirtualMachine) -> PyRef<PyStr> {
186+
self.into_ref(vm)
187+
}
188+
}
189+
190+
impl IntoPyStrRef for AsciiString {
173191
#[inline]
174-
fn try_into_ref(self, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>> {
175-
Ok(unsafe { PyStr::new_ascii_unchecked(self.into()) }.into_ref(vm))
192+
fn into_pystr_ref(self, vm: &VirtualMachine) -> PyRef<PyStr> {
193+
PyStr::from(self).into_ref(vm)
176194
}
177195
}
178196

179-
impl TryIntoRef<PyStr> for String {
197+
impl IntoPyStrRef for String {
180198
#[inline]
181-
fn try_into_ref(self, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>> {
182-
Ok(PyStr::from(self).into_ref(vm))
199+
fn into_pystr_ref(self, vm: &VirtualMachine) -> PyRef<PyStr> {
200+
PyStr::from(self).into_ref(vm)
183201
}
184202
}
185203

186-
impl TryIntoRef<PyStr> for &str {
204+
impl IntoPyStrRef for &str {
187205
#[inline]
188-
fn try_into_ref(self, vm: &VirtualMachine) -> PyResult<PyRef<PyStr>> {
189-
Ok(PyStr::from(self).into_ref(vm))
206+
fn into_pystr_ref(self, vm: &VirtualMachine) -> PyRef<PyStr> {
207+
PyStr::from(self).into_ref(vm)
190208
}
191209
}
192210

vm/src/builtins/slice.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@ use super::{PyInt, PyIntRef, PyTupleRef, PyTypeRef};
33
use crate::{
44
function::{FuncArgs, IntoPyObject, OptionalArg},
55
slots::{Comparable, Hashable, PyComparisonOp, SlotConstructor, Unhashable},
6-
PyClassImpl, PyComparisonValue, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TryIntoRef,
7-
TypeProtocol, VirtualMachine,
6+
PyClassImpl, PyComparisonValue, PyContext, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol,
7+
VirtualMachine,
88
};
99
use num_bigint::{BigInt, ToBigInt};
1010
use num_traits::{One, Signed, ToPrimitive, Zero};
@@ -115,7 +115,7 @@ impl PySlice {
115115
step = One::one();
116116
} else {
117117
// Clone the value, not the reference.
118-
let this_step: PyRef<PyInt> = self.step(vm).try_into_ref(vm)?;
118+
let this_step: PyRef<PyInt> = self.step(vm).try_into_value(vm)?;
119119
step = this_step.as_bigint().clone();
120120

121121
if step.is_zero() {
@@ -149,7 +149,7 @@ impl PySlice {
149149
lower.clone()
150150
};
151151
} else {
152-
let this_start: PyRef<PyInt> = self.start(vm).try_into_ref(vm)?;
152+
let this_start: PyRef<PyInt> = self.start(vm).try_into_value(vm)?;
153153
start = this_start.as_bigint().clone();
154154

155155
if start < Zero::zero() {
@@ -169,7 +169,7 @@ impl PySlice {
169169
if vm.is_none(&self.stop) {
170170
stop = if backwards { lower } else { upper };
171171
} else {
172-
let this_stop: PyRef<PyInt> = self.stop(vm).try_into_ref(vm)?;
172+
let this_stop: PyRef<PyInt> = self.stop(vm).try_into_value(vm)?;
173173
stop = this_stop.as_bigint().clone();
174174

175175
if stop < Zero::zero() {

vm/src/builtins/weakproxy.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,14 +47,14 @@ impl SlotConstructor for PyWeakProxy {
4747
impl PyWeakProxy {
4848
// TODO: callbacks
4949
#[pymethod(magic)]
50-
fn getattr(&self, attr_name: PyObjectRef, vm: &VirtualMachine) -> PyResult {
51-
match self.weak.upgrade() {
52-
Some(obj) => vm.get_attribute(obj, attr_name),
53-
None => Err(vm.new_exception_msg(
50+
fn getattr(&self, attr_name: PyStrRef, vm: &VirtualMachine) -> PyResult {
51+
let obj = self.weak.upgrade().ok_or_else(|| {
52+
vm.new_exception_msg(
5453
vm.ctx.exceptions.reference_error.clone(),
5554
"weakly-referenced object no longer exists".to_owned(),
56-
)),
57-
}
55+
)
56+
})?;
57+
vm.get_attribute(obj, attr_name)
5858
}
5959
}
6060

vm/src/pyobject.rs

Lines changed: 0 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -407,11 +407,6 @@ impl<T: PyValue> IntoPyObject for PyRefExact<T> {
407407
self.obj.into()
408408
}
409409
}
410-
impl<T: PyValue> TryIntoRef<T> for PyRefExact<T> {
411-
fn try_into_ref(self, _vm: &VirtualMachine) -> PyResult<PyRef<T>> {
412-
Ok(self.obj)
413-
}
414-
}
415410

416411
pub trait IdProtocol {
417412
fn get_id(&self) -> usize;
@@ -613,28 +608,6 @@ impl<T: TryFromObject> TryFromObject for Option<T> {
613608
}
614609
}
615610

616-
/// Allows coercion of a types into PyRefs, so that we can write functions that can take
617-
/// refs, pyobject refs or basic types.
618-
pub trait TryIntoRef<T: PyObjectPayload> {
619-
fn try_into_ref(self, vm: &VirtualMachine) -> PyResult<PyRef<T>>;
620-
}
621-
622-
impl<T: PyObjectPayload> TryIntoRef<T> for PyRef<T> {
623-
#[inline]
624-
fn try_into_ref(self, _vm: &VirtualMachine) -> PyResult<PyRef<T>> {
625-
Ok(self)
626-
}
627-
}
628-
629-
impl<T> TryIntoRef<T> for PyObjectRef
630-
where
631-
T: PyValue,
632-
{
633-
fn try_into_ref(self, vm: &VirtualMachine) -> PyResult<PyRef<T>> {
634-
TryFromObject::try_from_object(vm, self)
635-
}
636-
}
637-
638611
/// Implemented by any type that can be created from a Python object.
639612
///
640613
/// Any type that implements `TryFromObject` is automatically `FromArgs`, and

vm/src/scope.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1+
use crate::{
2+
builtins::{pystr::IntoPyStrRef, PyDictRef, PyStrRef},
3+
function::IntoPyObject,
4+
ItemProtocol, VirtualMachine,
5+
};
16
use std::fmt;
27

3-
use crate::builtins::{PyDictRef, PyStr, PyStrRef};
4-
use crate::function::IntoPyObject;
5-
use crate::VirtualMachine;
6-
use crate::{ItemProtocol, TryIntoRef};
7-
88
#[derive(Clone)]
99
pub struct Scope {
1010
pub locals: PyDictRef,
@@ -145,7 +145,7 @@ mod sealed {
145145
impl Sealed for super::PyStrRef {}
146146
}
147147
pub trait PyName:
148-
sealed::Sealed + crate::dictdatatype::DictKey + Clone + IntoPyObject + TryIntoRef<PyStr>
148+
sealed::Sealed + crate::dictdatatype::DictKey + Clone + IntoPyObject + IntoPyStrRef
149149
{
150150
}
151151
impl PyName for &str {}

vm/src/stdlib/errno.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
77
"errorcode" => errorcode.clone(),
88
});
99
for (name, code) in ERROR_CODES {
10-
let name = vm.new_pyobj(*name);
10+
let name = vm.ctx.new_str(*name);
1111
let code = vm.new_pyobj(*code);
12-
errorcode.set_item(code.clone(), name.clone(), vm).unwrap();
12+
errorcode
13+
.set_item(code.clone(), name.clone().into(), vm)
14+
.unwrap();
1315
vm.set_attr(&module, name, code).unwrap();
1416
}
1517
module

vm/src/stdlib/operator.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ mod _operator {
2121
},
2222
utils::Either,
2323
vm::ReprGuard,
24-
IdProtocol, ItemProtocol, PyObjectRef, PyRef, PyResult, PyValue, TryIntoRef, TypeProtocol,
24+
IdProtocol, ItemProtocol, PyObjectRef, PyRef, PyResult, PyValue, TypeProtocol,
2525
VirtualMachine,
2626
};
2727

@@ -444,7 +444,7 @@ mod _operator {
444444
}
445445
let mut attrs = Vec::with_capacity(nattr);
446446
for o in args.args {
447-
if let Ok(r) = o.try_into_ref(vm) {
447+
if let Ok(r) = o.try_into_value(vm) {
448448
attrs.push(r);
449449
} else {
450450
return Err(vm.new_type_error("attribute name must be a string".to_owned()));
@@ -598,7 +598,7 @@ mod _operator {
598598
type Args = (PyObjectRef, FuncArgs);
599599

600600
fn py_new(cls: PyTypeRef, (name, args): Self::Args, vm: &VirtualMachine) -> PyResult {
601-
if let Ok(name) = name.try_into_ref(vm) {
601+
if let Ok(name) = name.try_into_value(vm) {
602602
PyMethodCaller { name, args }.into_pyresult_with_type(vm, cls)
603603
} else {
604604
Err(vm.new_type_error("method name must be a string".to_owned()))

vm/src/vm.rs

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use crate::{
1010
builtins::{
1111
code::{self, PyCode},
1212
module, object,
13+
pystr::IntoPyStrRef,
1314
tuple::{IntoPyTuple, PyTuple, PyTupleRef, PyTupleTyped},
1415
PyBaseException, PyBaseExceptionRef, PyDictRef, PyInt, PyIntRef, PyList, PyModule, PyStr,
1516
PyStrRef, PyTypeRef,
@@ -29,7 +30,7 @@ use crate::{
2930
stdlib,
3031
utils::Either,
3132
IdProtocol, ItemProtocol, PyArithmeticValue, PyContext, PyLease, PyMethod, PyObject,
32-
PyObjectRef, PyRef, PyRefExact, PyResult, PyValue, TryFromObject, TryIntoRef, TypeProtocol,
33+
PyObjectRef, PyRef, PyRefExact, PyResult, PyValue, TryFromObject, TypeProtocol,
3334
};
3435
use crossbeam_utils::atomic::AtomicCell;
3536
use num_traits::{Signed, ToPrimitive};
@@ -800,14 +801,10 @@ impl VirtualMachine {
800801
syntax_error
801802
}
802803

803-
pub fn new_import_error(
804-
&self,
805-
msg: String,
806-
name: impl TryIntoRef<PyStr>,
807-
) -> PyBaseExceptionRef {
804+
pub fn new_import_error(&self, msg: String, name: impl IntoPyStrRef) -> PyBaseExceptionRef {
808805
let import_error = self.ctx.exceptions.import_error.clone();
809806
let exc = self.new_exception_msg(import_error, msg);
810-
self.set_attr(exc.as_object(), "name", name.try_into_ref(self).unwrap())
807+
self.set_attr(exc.as_object(), "name", name.into_pystr_ref(self))
811808
.unwrap();
812809
exc
813810
}
@@ -938,11 +935,11 @@ impl VirtualMachine {
938935
#[inline]
939936
pub fn import(
940937
&self,
941-
module: impl TryIntoRef<PyStr>,
938+
module: impl IntoPyStrRef,
942939
from_list: Option<PyTupleTyped<PyStrRef>>,
943940
level: usize,
944941
) -> PyResult {
945-
self._import_inner(module.try_into_ref(self)?, from_list, level)
942+
self._import_inner(module.into_pystr_ref(self), from_list, level)
946943
}
947944

948945
fn _import_inner(
@@ -1399,9 +1396,9 @@ impl VirtualMachine {
13991396
#[cfg_attr(feature = "flame-it", flame("VirtualMachine"))]
14001397
pub fn get_attribute<T>(&self, obj: PyObjectRef, attr_name: T) -> PyResult
14011398
where
1402-
T: TryIntoRef<PyStr>,
1399+
T: IntoPyStrRef,
14031400
{
1404-
let attr_name = attr_name.try_into_ref(self)?;
1401+
let attr_name = attr_name.into_pystr_ref(self);
14051402
vm_trace!("vm.__getattribute__: {:?} {:?}", obj, attr_name);
14061403
let getattro = obj
14071404
.class()
@@ -1416,7 +1413,7 @@ impl VirtualMachine {
14161413
attr_name: T,
14171414
) -> PyResult<Option<PyObjectRef>>
14181415
where
1419-
T: TryIntoRef<PyStr>,
1416+
T: IntoPyStrRef,
14201417
{
14211418
match self.get_attribute(obj, attr_name) {
14221419
Ok(attr) => Ok(Some(attr)),
@@ -1451,15 +1448,15 @@ impl VirtualMachine {
14511448

14521449
pub fn set_attr<K, V>(&self, obj: &PyObjectRef, attr_name: K, attr_value: V) -> PyResult<()>
14531450
where
1454-
K: TryIntoRef<PyStr>,
1451+
K: IntoPyStrRef,
14551452
V: Into<PyObjectRef>,
14561453
{
1457-
let attr_name = attr_name.try_into_ref(self)?;
1454+
let attr_name = attr_name.into_pystr_ref(self);
14581455
self.call_set_attr(obj, attr_name, Some(attr_value.into()))
14591456
}
14601457

1461-
pub fn del_attr(&self, obj: &PyObjectRef, attr_name: impl TryIntoRef<PyStr>) -> PyResult<()> {
1462-
let attr_name = attr_name.try_into_ref(self)?;
1458+
pub fn del_attr(&self, obj: &PyObjectRef, attr_name: impl IntoPyStrRef) -> PyResult<()> {
1459+
let attr_name = attr_name.into_pystr_ref(self);
14631460
self.call_set_attr(obj, attr_name, None)
14641461
}
14651462

@@ -2169,11 +2166,11 @@ impl VirtualMachine {
21692166
pub fn __module_set_attr(
21702167
&self,
21712168
module: &PyObjectRef,
2172-
attr_name: impl TryIntoRef<PyStr>,
2169+
attr_name: impl IntoPyStrRef,
21732170
attr_value: impl Into<PyObjectRef>,
21742171
) -> PyResult<()> {
21752172
let val = attr_value.into();
2176-
object::setattr(module, attr_name.try_into_ref(self)?, Some(val), self)
2173+
object::setattr(module, attr_name.into_pystr_ref(self), Some(val), self)
21772174
}
21782175
}
21792176

0 commit comments

Comments
 (0)