Remove useless &PyRef patterns (#6455)

* fix &PyTypeRef

* Remove useless &PyObjectRef

* Remove useless &PyRef
This commit is contained in:
Jeong, YunWon authored and GitHub committed 2025-12-17 20:58:00 +09:00
1 parent 0412dfdb3b
commit a4c93dfbbf
37 files changed
+146 -137

No files matched your search

+8 -10
View File
@@ -4,7 +4,8 @@ pub(crate) use _csv::make_module;
mod _csv {
use crate::common::lock::PyMutex;
use crate::vm::{
AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
VirtualMachine,
builtins::{PyBaseExceptionRef, PyInt, PyNone, PyStr, PyType, PyTypeRef},
function::{ArgIterable, ArgumentError, FromArgs, FuncArgs, OptionalArg},
protocol::{PyIter, PyIterReturn},
@@ -130,11 +131,11 @@ mod _csv {
///
/// * If the 'delimiter' attribute is not a single-character string, a type error is returned.
/// * If the 'obj' is not of string type and does not have a 'delimiter' attribute, a type error is returned.
fn parse_delimiter_from_obj(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<u8> {
fn parse_delimiter_from_obj(vm: &VirtualMachine, obj: &PyObject) -> PyResult<u8> {
if let Ok(attr) = obj.get_attr("delimiter", vm) {
parse_delimiter_from_obj(vm, &attr)
} else {
match_class!(match obj.clone() {
match_class!(match obj.to_owned() {
s @ PyStr => {
Ok(s.as_str().bytes().exactly_one().map_err(|_| {
let msg = r#""delimiter" must be a 1-character string"#;
@@ -148,7 +149,7 @@ mod _csv {
})
}
}
fn parse_quotechar_from_obj(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<Option<u8>> {
fn parse_quotechar_from_obj(vm: &VirtualMachine, obj: &PyObject) -> PyResult<Option<u8>> {
match_class!(match obj.get_attr("quotechar", vm)? {
s @ PyStr => {
Ok(Some(s.as_str().bytes().exactly_one().map_err(|_| {
@@ -169,7 +170,7 @@ mod _csv {
}
})
}
fn parse_escapechar_from_obj(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<Option<u8>> {
fn parse_escapechar_from_obj(vm: &VirtualMachine, obj: &PyObject) -> PyResult<Option<u8>> {
match_class!(match obj.get_attr("escapechar", vm)? {
s @ PyStr => {
Ok(Some(s.as_str().bytes().exactly_one().map_err(|_| {
@@ -191,10 +192,7 @@ mod _csv {
}
})
}
fn prase_lineterminator_from_obj(
vm: &VirtualMachine,
obj: &PyObjectRef,
) -> PyResult<Terminator> {
fn prase_lineterminator_from_obj(vm: &VirtualMachine, obj: &PyObject) -> PyResult<Terminator> {
match_class!(match obj.get_attr("lineterminator", vm)? {
s @ PyStr => {
Ok(if s.as_bytes().eq(b"\r\n") {
@@ -217,7 +215,7 @@ mod _csv {
}
})
}
fn prase_quoting_from_obj(vm: &VirtualMachine, obj: &PyObjectRef) -> PyResult<QuoteStyle> {
fn prase_quoting_from_obj(vm: &VirtualMachine, obj: &PyObject) -> PyResult<QuoteStyle> {
match_class!(match obj.get_attr("quoting", vm)? {
i @ PyInt => {
Ok(i.try_to_primitive::<isize>(vm)?.try_into().map_err(|_| {
+3 -2
View File
@@ -56,7 +56,8 @@ mod _ssl {
vm::{
AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
builtins::{
PyBaseExceptionRef, PyBytesRef, PyListRef, PyOSError, PyStrRef, PyTypeRef, PyWeak,
PyBaseException, PyBaseExceptionRef, PyBytesRef, PyListRef, PyOSError, PyStrRef,
PyTypeRef, PyWeak,
},
class_or_notimplemented,
convert::ToPyException,
@@ -3351,7 +3352,7 @@ mod _ssl {
// Helper function to set verify_code and verify_message on SSLCertVerificationError
fn set_verify_error_info(
exc: &PyBaseExceptionRef,
exc: &Py<PyBaseException>,
ssl_ptr: *const sys::SSL,
vm: &VirtualMachine,
) {
+3 -3
View File
@@ -5,8 +5,8 @@ mod _scproxy {
// straight-forward port of Modules/_scproxy.c
use crate::vm::{
PyResult, VirtualMachine,
builtins::{PyDictRef, PyStr},
Py, PyResult, VirtualMachine,
builtins::{PyDict, PyDictRef, PyStr},
convert::ToPyObject,
};
use system_configuration::core_foundation::{
@@ -74,7 +74,7 @@ mod _scproxy {
let result = vm.ctx.new_dict();
let set_proxy = |result: &PyDictRef,
let set_proxy = |result: &Py<PyDict>,
proto: &str,
enabled_key: CFStringRef,
host_key: CFStringRef,
+7 -7
View File
@@ -1423,7 +1423,7 @@ mod _ssl {
/// Helper: Get path from Python's os.environ
fn get_env_path(
environ: &PyObjectRef,
environ: &PyObject,
var_name: &str,
vm: &VirtualMachine,
) -> PyResult<String> {
@@ -2101,10 +2101,10 @@ mod _ssl {
// Helper functions (private):
/// Parse path argument (str or bytes) to string
fn parse_path_arg(arg: &PyObjectRef, vm: &VirtualMachine) -> PyResult<String> {
if let Ok(s) = PyStrRef::try_from_object(vm, arg.clone()) {
fn parse_path_arg(arg: &PyObject, vm: &VirtualMachine) -> PyResult<String> {
if let Ok(s) = PyStrRef::try_from_object(vm, arg.to_owned()) {
Ok(s.as_str().to_owned())
} else if let Ok(b) = ArgBytesLike::try_from_object(vm, arg.clone()) {
} else if let Ok(b) = ArgBytesLike::try_from_object(vm, arg.to_owned()) {
String::from_utf8(b.borrow_buf().to_vec())
.map_err(|_| vm.new_value_error("path contains invalid UTF-8".to_owned()))
} else {
@@ -2279,10 +2279,10 @@ mod _ssl {
}
/// Helper: Parse cadata argument (str or bytes)
fn parse_cadata_arg(&self, arg: &PyObjectRef, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
if let Ok(s) = PyStrRef::try_from_object(vm, arg.clone()) {
fn parse_cadata_arg(&self, arg: &PyObject, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
if let Ok(s) = PyStrRef::try_from_object(vm, arg.to_owned()) {
Ok(s.as_str().as_bytes().to_vec())
} else if let Ok(b) = ArgBytesLike::try_from_object(vm, arg.clone()) {
} else if let Ok(b) = ArgBytesLike::try_from_object(vm, arg.to_owned()) {
Ok(b.borrow_buf().to_vec())
} else {
Err(vm.new_type_error("cadata should be a str or bytes".to_owned()))
+4 -4
View File
@@ -23,10 +23,10 @@ use rustls::server::ResolvesServerCert;
use rustls::server::ServerConfig;
use rustls::server::ServerConnection;
use rustls::sign::CertifiedKey;
use rustpython_vm::builtins::PyBaseExceptionRef;
use rustpython_vm::builtins::{PyBaseException, PyBaseExceptionRef};
use rustpython_vm::convert::IntoPyException;
use rustpython_vm::function::ArgBytesLike;
use rustpython_vm::{AsObject, PyObjectRef, PyPayload, PyResult, TryFromObject};
use rustpython_vm::{AsObject, Py, PyObjectRef, PyPayload, PyResult, TryFromObject};
use std::io::Read;
use std::sync::{Arc, Once};
@@ -984,7 +984,7 @@ pub(super) fn create_client_config(options: ClientConfigOptions) -> Result<Clien
}
/// Helper function - check if error is BlockingIOError
pub(super) fn is_blocking_io_error(err: &PyBaseExceptionRef, vm: &VirtualMachine) -> bool {
pub(super) fn is_blocking_io_error(err: &Py<PyBaseException>, vm: &VirtualMachine) -> bool {
err.fast_isinstance(vm.ctx.exceptions.blocking_io_error)
}
@@ -1534,7 +1534,7 @@ fn ssl_read_tls_records(
/// Check if an exception is a connection closed error
/// In SSL context, these errors indicate unexpected connection termination without proper TLS shutdown
fn is_connection_closed_error(exc: &PyBaseExceptionRef, vm: &VirtualMachine) -> bool {
fn is_connection_closed_error(exc: &Py<PyBaseException>, vm: &VirtualMachine) -> bool {
use rustpython_vm::stdlib::errno::errors;
// Check for ConnectionAbortedError, ConnectionResetError (Python exception types)
+2 -2
View File
@@ -51,11 +51,11 @@ impl PyNativeFunction {
}
// PyCFunction_GET_SELF
pub const fn get_self(&self) -> Option<&PyObjectRef> {
pub fn get_self(&self) -> Option<&PyObject> {
if self.value.flags.contains(PyMethodFlags::STATIC) {
return None;
}
self.zelf.as_ref()
self.zelf.as_deref()
}
pub const fn as_func(&self) -> &'static dyn PyNativeFn {
+5 -5
View File
@@ -753,7 +753,7 @@ impl ExactSizeIterator for DictIter<'_> {
trait DictView: PyPayload + PyClassDef + Iterable + Representable {
type ReverseIter: PyPayload + std::fmt::Debug;
fn dict(&self) -> &PyDictRef;
fn dict(&self) -> &Py<PyDict>;
fn item(vm: &VirtualMachine, key: PyObjectRef, value: PyObjectRef) -> PyObjectRef;
#[pymethod]
@@ -785,7 +785,7 @@ macro_rules! dict_view {
impl DictView for $name {
type ReverseIter = $reverse_iter_name;
fn dict(&self) -> &PyDictRef {
fn dict(&self) -> &Py<PyDict> {
&self.dict
}
@@ -1142,7 +1142,7 @@ impl PyDictKeys {
#[pygetset]
fn mapping(zelf: PyRef<Self>) -> PyMappingProxy {
PyMappingProxy::from(zelf.dict().clone())
PyMappingProxy::from(zelf.dict().to_owned())
}
}
@@ -1206,7 +1206,7 @@ impl PyDictItems {
}
#[pygetset]
fn mapping(zelf: PyRef<Self>) -> PyMappingProxy {
PyMappingProxy::from(zelf.dict().clone())
PyMappingProxy::from(zelf.dict().to_owned())
}
}
@@ -1269,7 +1269,7 @@ impl AsNumber for PyDictItems {
impl PyDictValues {
#[pygetset]
fn mapping(zelf: PyRef<Self>) -> PyMappingProxy {
PyMappingProxy::from(zelf.dict().clone())
PyMappingProxy::from(zelf.dict().to_owned())
}
}
+4 -2
View File
@@ -1,6 +1,8 @@
use crate::{
AsObject, Py, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine,
builtins::{PyBaseExceptionRef, PyDictRef, PyFunction, PyStrInterned, bool_, float, int},
builtins::{
PyBaseExceptionRef, PyDict, PyDictRef, PyFunction, PyStrInterned, bool_, float, int,
},
bytecode::CodeFlags,
convert::ToPyObject,
function::FuncArgs,
@@ -42,7 +44,7 @@ pub fn new_jit_error(msg: String, vm: &VirtualMachine) -> PyBaseExceptionRef {
vm.new_exception_msg(jit_error, msg)
}
fn get_jit_arg_type(dict: &PyDictRef, name: &str, vm: &VirtualMachine) -> PyResult<JitType> {
fn get_jit_arg_type(dict: &Py<PyDict>, name: &str, vm: &VirtualMachine) -> PyResult<JitType> {
if let Some(value) = dict.get_item_opt(name, vm)? {
if value.is(vm.ctx.types.int_type) {
Ok(JitType::Int)
+3 -3
View File
@@ -294,11 +294,11 @@ pub(crate) fn make_parameters(args: &Py<PyTuple>, vm: &VirtualMachine) -> PyTupl
}
#[inline]
fn tuple_index(vec: &[PyObjectRef], item: &PyObjectRef) -> Option<usize> {
fn tuple_index(vec: &[PyObjectRef], item: &PyObject) -> Option<usize> {
vec.iter().position(|element| element.is(item))
}
fn is_unpacked_typevartuple(arg: &PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
fn is_unpacked_typevartuple(arg: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
if arg.class().is(vm.ctx.types.type_type) {
return Ok(false);
}
@@ -312,7 +312,7 @@ fn is_unpacked_typevartuple(arg: &PyObjectRef, vm: &VirtualMachine) -> PyResult<
fn subs_tvars(
obj: PyObjectRef,
params: &PyTupleRef,
params: &Py<PyTuple>,
arg_items: &[PyObjectRef],
vm: &VirtualMachine,
) -> PyResult {
+2 -2
View File
@@ -367,8 +367,8 @@ where
impl MutObjectSequenceOp for PyList {
type Inner = [PyObjectRef];
fn do_get(index: usize, inner: &[PyObjectRef]) -> Option<&PyObjectRef> {
inner.get(index)
fn do_get(index: usize, inner: &[PyObjectRef]) -> Option<&PyObject> {
inner.get(index).map(|r| r.as_ref())
}
fn do_lock(&self) -> impl std::ops::Deref<Target = [PyObjectRef]> {
+3 -3
View File
@@ -266,7 +266,7 @@ impl PyProperty {
#[pygetset]
fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyResult {
// Helper to check if a method is abstract
let is_abstract = |method: &PyObjectRef| -> PyResult<bool> {
let is_abstract = |method: &PyObject| -> PyResult<bool> {
match method.get_attr("__isabstractmethod__", vm) {
Ok(isabstract) => isabstract.try_to_bool(vm),
Err(_) => Ok(false),
@@ -309,7 +309,7 @@ impl PyProperty {
#[cold]
fn format_property_error(
&self,
obj: &PyObjectRef,
obj: &PyObject,
error_type: &str,
vm: &VirtualMachine,
) -> PyResult<String> {
@@ -356,7 +356,7 @@ impl Initializer for PyProperty {
let mut getter_doc = false;
// Helper to get doc from getter
let get_getter_doc = |fget: &PyObjectRef| -> Option<PyObjectRef> {
let get_getter_doc = |fget: &PyObject| -> Option<PyObjectRef> {
fget.get_attr("__doc__", vm)
.ok()
.filter(|doc| !vm.is_none(doc))
+2 -2
View File
@@ -175,12 +175,12 @@ fn is_subtype_with_mro(a_mro: &[PyTypeRef], a: &Py<PyType>, b: &Py<PyType>) -> b
impl PyType {
pub fn new_simple_heap(
name: &str,
base: &PyTypeRef,
base: &Py<PyType>,
ctx: &Context,
) -> Result<PyRef<Self>, String> {
Self::new_heap(
name,
vec![base.clone()],
vec![base.to_owned()],
Default::default(),
Default::default(),
Self::static_type().to_owned(),
+1 -1
View File
@@ -42,7 +42,7 @@ impl PyUnion {
/// Direct access to args field, matching CPython's _Py_union_args
#[inline]
pub const fn args(&self) -> &PyTupleRef {
pub fn args(&self) -> &Py<PyTuple> {
&self.args
}
+10 -6
View File
@@ -6,7 +6,8 @@
use crate::common::cformat::*;
use crate::common::wtf8::{CodePoint, Wtf8, Wtf8Buf};
use crate::{
AsObject, PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine,
AsObject, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject,
VirtualMachine,
builtins::{
PyBaseExceptionRef, PyByteArray, PyBytes, PyFloat, PyInt, PyStr, try_f64_to_bigint, tuple,
},
@@ -207,7 +208,7 @@ fn spec_format_string(
fn try_update_quantity_from_element(
vm: &VirtualMachine,
element: Option<&PyObjectRef>,
element: Option<&PyObject>,
) -> PyResult<CFormatQuantity> {
match element {
Some(width_obj) => {
@@ -224,7 +225,7 @@ fn try_update_quantity_from_element(
fn try_conversion_flag_from_tuple(
vm: &VirtualMachine,
element: Option<&PyObjectRef>,
element: Option<&PyObject>,
) -> PyResult<CConversionFlags> {
match element {
Some(width_obj) => {
@@ -254,8 +255,11 @@ fn try_update_quantity_from_tuple<'a, I: Iterator<Item = &'a PyObjectRef>>(
return Ok(());
};
let element = elements.next();
f.insert(try_conversion_flag_from_tuple(vm, element)?);
let quantity = try_update_quantity_from_element(vm, element)?;
f.insert(try_conversion_flag_from_tuple(
vm,
element.map(|v| v.as_ref()),
)?);
let quantity = try_update_quantity_from_element(vm, element.map(|v| v.as_ref()))?;
*q = Some(quantity);
Ok(())
}
@@ -268,7 +272,7 @@ fn try_update_precision_from_tuple<'a, I: Iterator<Item = &'a PyObjectRef>>(
let Some(CFormatPrecision::Quantity(CFormatQuantity::FromValuesTuple)) = p else {
return Ok(());
};
let quantity = try_update_quantity_from_element(vm, elements.next())?;
let quantity = try_update_quantity_from_element(vm, elements.next().map(|v| v.as_ref()))?;
*p = Some(CFormatPrecision::Quantity(quantity));
Ok(())
}
+1 -1
View File
@@ -52,7 +52,7 @@ impl PyCodec {
self.0
}
#[inline]
pub const fn as_tuple(&self) -> &PyTupleRef {
pub fn as_tuple(&self) -> &Py<PyTuple> {
&self.0
}
+3 -2
View File
@@ -1,7 +1,8 @@
use crate::{
AsObject, PyObject, PyObjectRef, PyResult, VirtualMachine,
AsObject, Py, PyObject, PyObjectRef, PyResult, VirtualMachine,
builtins::{PyBaseExceptionRef, PyStrRef},
common::lock::PyMutex,
exceptions::types::PyBaseException,
frame::{ExecutionResult, FrameRef},
protocol::PyIterReturn,
};
@@ -207,6 +208,6 @@ impl Coro {
}
}
pub fn is_gen_exit(exc: &PyBaseExceptionRef, vm: &VirtualMachine) -> bool {
pub fn is_gen_exit(exc: &Py<PyBaseException>, vm: &VirtualMachine) -> bool {
exc.fast_isinstance(vm.ctx.exceptions.generator_exit)
}
+7 -7
View File
@@ -352,12 +352,12 @@ pub(super) mod types {
}
// Helper functions for ExceptionGroup
fn is_base_exception_group(obj: &PyObjectRef, vm: &VirtualMachine) -> bool {
fn is_base_exception_group(obj: &PyObject, vm: &VirtualMachine) -> bool {
obj.fast_isinstance(vm.ctx.exceptions.base_exception_group)
}
fn get_exceptions_tuple(
exc: &PyRef<PyBaseException>,
exc: &Py<PyBaseException>,
vm: &VirtualMachine,
) -> PyResult<Vec<PyObjectRef>> {
let obj = exc
@@ -376,7 +376,7 @@ pub(super) mod types {
}
fn get_condition_matcher(
condition: &PyObjectRef,
condition: &PyObject,
vm: &VirtualMachine,
) -> PyResult<ConditionMatcher> {
// If it's a type and subclass of BaseException
@@ -409,19 +409,19 @@ pub(super) mod types {
// If it's callable (but not a type)
if condition.is_callable() && condition.downcast_ref::<PyType>().is_none() {
return Ok(ConditionMatcher::Callable(condition.clone()));
return Ok(ConditionMatcher::Callable(condition.to_owned()));
}
Err(vm.new_type_error("expected a function, exception type or tuple of exception types"))
}
impl ConditionMatcher {
fn check(&self, exc: &PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
fn check(&self, exc: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
match self {
ConditionMatcher::Type(typ) => Ok(exc.fast_isinstance(typ)),
ConditionMatcher::Types(types) => Ok(types.iter().any(|t| exc.fast_isinstance(t))),
ConditionMatcher::Callable(func) => {
let result = func.call((exc.clone(),), vm)?;
let result = func.call((exc.to_owned(),), vm)?;
result.try_to_bool(vm)
}
}
@@ -429,7 +429,7 @@ pub(super) mod types {
}
fn derive_and_copy_attributes(
orig: &PyRef<PyBaseException>,
orig: &Py<PyBaseException>,
excs: Vec<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<PyObjectRef> {
+7 -7
View File
@@ -79,7 +79,7 @@ impl VirtualMachine {
pub fn write_exception<W: Write>(
&self,
output: &mut W,
exc: &PyBaseExceptionRef,
exc: &Py<PyBaseException>,
) -> Result<(), W::Error> {
let seen = &mut HashSet::<usize>::new();
self.write_exception_recursive(output, exc, seen)
@@ -88,7 +88,7 @@ impl VirtualMachine {
fn write_exception_recursive<W: Write>(
&self,
output: &mut W,
exc: &PyBaseExceptionRef,
exc: &Py<PyBaseException>,
seen: &mut HashSet<usize>,
) -> Result<(), W::Error> {
// This function should not be called directly,
@@ -132,7 +132,7 @@ impl VirtualMachine {
pub fn write_exception_inner<W: Write>(
&self,
output: &mut W,
exc: &PyBaseExceptionRef,
exc: &Py<PyBaseException>,
) -> Result<(), W::Error> {
let vm = self;
if let Some(tb) = exc.traceback.read().clone() {
@@ -177,7 +177,7 @@ impl VirtualMachine {
fn write_syntaxerror<W: Write>(
&self,
output: &mut W,
exc: &PyBaseExceptionRef,
exc: &Py<PyBaseException>,
exc_type: &Py<PyType>,
args_repr: &[PyRef<PyStr>],
) -> Result<(), W::Error> {
@@ -369,7 +369,7 @@ fn print_source_line<W: Write>(
/// Print exception occurrence location from traceback element
fn write_traceback_entry<W: Write>(
output: &mut W,
tb_entry: &PyTracebackRef,
tb_entry: &Py<PyTraceback>,
) -> Result<(), W::Error> {
let filename = tb_entry.frame.code.source_path.as_str();
writeln!(
@@ -1053,12 +1053,12 @@ fn system_exit_code(exc: PyBaseExceptionRef) -> Option<PyObjectRef> {
#[cfg(feature = "serde")]
pub struct SerializeException<'vm, 's> {
vm: &'vm VirtualMachine,
exc: &'s PyBaseExceptionRef,
exc: &'s Py<PyBaseException>,
}
#[cfg(feature = "serde")]
impl<'vm, 's> SerializeException<'vm, 's> {
pub fn new(vm: &'vm VirtualMachine, exc: &'s PyBaseExceptionRef) -> Self {
pub fn new(vm: &'vm VirtualMachine, exc: &'s Py<PyBaseException>) -> Self {
SerializeException { vm, exc }
}
}
+2 -2
View File
@@ -1866,14 +1866,14 @@ impl ExecutingFrame<'_> {
/// This ensures proper order preservation for OrderedDict and other custom mappings.
fn iterate_mapping_keys<F>(
vm: &VirtualMachine,
mapping: &PyObjectRef,
mapping: &PyObject,
error_prefix: &str,
mut key_handler: F,
) -> PyResult<()>
where
F: FnMut(PyObjectRef) -> PyResult<()>,
{
let Some(keys_method) = vm.get_method(mapping.clone(), vm.ctx.intern_str("keys")) else {
let Some(keys_method) = vm.get_method(mapping.to_owned(), vm.ctx.intern_str("keys")) else {
return Err(vm.new_type_error(format!("{error_prefix} must be a mapping")));
};
+4 -3
View File
@@ -1,8 +1,9 @@
//! Import mechanics
use crate::{
AsObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
builtins::{PyBaseExceptionRef, PyCode, list, traceback::PyTraceback},
AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
builtins::{PyCode, list, traceback::PyTraceback},
exceptions::types::PyBaseException,
scope::Scope,
version::get_git_revision,
vm::{VirtualMachine, thread},
@@ -204,7 +205,7 @@ fn remove_importlib_frames_inner(
// TODO: This function should do nothing on verbose mode.
// TODO: Fix this function after making PyTraceback.next mutable
pub fn remove_importlib_frames(vm: &VirtualMachine, exc: &PyBaseExceptionRef) {
pub fn remove_importlib_frames(vm: &VirtualMachine, exc: &Py<PyBaseException>) {
if vm.state.settings.verbose != 0 {
return;
}
+2 -2
View File
@@ -106,7 +106,7 @@ pub trait PyPayload: MaybeTraverse + PyThreadingConstraint + Sized + 'static {
#[inline(never)]
fn _into_ref_size_error(
vm: &VirtualMachine,
cls: &PyTypeRef,
cls: &Py<PyType>,
exact_class: &Py<PyType>,
) -> PyBaseExceptionRef {
vm.new_type_error(format!(
@@ -123,7 +123,7 @@ pub trait PyPayload: MaybeTraverse + PyThreadingConstraint + Sized + 'static {
#[inline(never)]
fn _into_ref_with_type_error(
vm: &VirtualMachine,
cls: &PyTypeRef,
cls: &Py<PyType>,
exact_class: &Py<PyType>,
) -> PyBaseExceptionRef {
vm.new_type_error(format!(
+1 -1
View File
@@ -34,7 +34,7 @@ impl Scope {
Self::new(locals, globals)
}
// pub fn get_locals(&self) -> &PyDictRef {
// pub fn get_locals(&self) -> &Py<PyDict> {
// match self.locals.first() {
// Some(dict) => dict,
// None => &self.globals,
+2 -2
View File
@@ -12,7 +12,7 @@ use std::ops::{Deref, Range};
pub trait MutObjectSequenceOp {
type Inner: ?Sized;
fn do_get(index: usize, inner: &Self::Inner) -> Option<&PyObjectRef>;
fn do_get(index: usize, inner: &Self::Inner) -> Option<&PyObject>;
fn do_lock(&self) -> impl Deref<Target = Self::Inner>;
fn mut_count(&self, vm: &VirtualMachine, needle: &PyObject) -> PyResult<usize> {
@@ -76,7 +76,7 @@ pub trait MutObjectSequenceOp {
}
borrower = Some(guard);
} else {
let elem = elem.clone();
let elem = elem.to_owned();
drop(guard);
if elem.rich_compare_bool(needle, PyComparisonOp::Eq, vm)? {
+2 -2
View File
@@ -10,7 +10,7 @@ mod builtins {
use std::io::IsTerminal;
use crate::{
AsObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
AsObject, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
builtins::{
PyByteArray, PyBytes, PyDictRef, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType,
enumerate::PyReverseSequenceIterator,
@@ -261,7 +261,7 @@ mod builtins {
func_name: &'static str,
) -> PyResult<crate::scope::Scope> {
fn validate_globals_dict(
globals: &PyObjectRef,
globals: &PyObject,
vm: &VirtualMachine,
func_name: &'static str,
) -> PyResult<()> {
+2 -2
View File
@@ -422,8 +422,8 @@ mod _collections {
impl MutObjectSequenceOp for PyDeque {
type Inner = VecDeque<PyObjectRef>;
fn do_get(index: usize, inner: &Self::Inner) -> Option<&PyObjectRef> {
inner.get(index)
fn do_get(index: usize, inner: &Self::Inner) -> Option<&PyObject> {
inner.get(index).map(|r| r.as_ref())
}
fn do_lock(&self) -> impl std::ops::Deref<Target = Self::Inner> {
+2 -2
View File
@@ -53,7 +53,7 @@ pub(crate) mod _ctypes {
use crate::convert::ToPyObject;
use crate::function::{Either, FuncArgs, OptionalArg};
use crate::stdlib::ctypes::library;
use crate::{AsObject, PyObjectRef, PyPayload, PyResult, VirtualMachine};
use crate::{AsObject, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine};
use crossbeam_utils::atomic::AtomicCell;
use std::ffi::{
c_double, c_float, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, c_ulong,
@@ -349,7 +349,7 @@ pub(crate) mod _ctypes {
const SIMPLE_TYPE_CHARS: &str = "cbBhHiIlLdfguzZPqQ?O";
pub fn new_simple_type(
cls: Either<&PyObjectRef, &PyTypeRef>,
cls: Either<&PyObject, &PyTypeRef>,
vm: &VirtualMachine,
) -> PyResult<PyCSimple> {
let cls = match cls {
+27 -25
View File
@@ -5,7 +5,9 @@ use crate::function::{ArgBytesLike, Either, FuncArgs, KwArgs, OptionalArg};
use crate::protocol::{BufferDescriptor, BufferMethods, PyBuffer, PyNumberMethods};
use crate::stdlib::ctypes::_ctypes::new_simple_type;
use crate::types::{AsBuffer, AsNumber, Constructor};
use crate::{AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine};
use crate::{
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
};
use crossbeam_utils::atomic::AtomicCell;
use num_traits::ToPrimitive;
use rustpython_common::lock::PyRwLock;
@@ -46,19 +48,19 @@ pub fn ffi_type_from_str(_type_: &str) -> Option<libffi::middle::Type> {
}
#[allow(dead_code)]
fn set_primitive(_type_: &str, value: &PyObjectRef, vm: &VirtualMachine) -> PyResult {
fn set_primitive(_type_: &str, value: &PyObject, vm: &VirtualMachine) -> PyResult {
match _type_ {
"c" => {
if value
.clone()
.to_owned()
.downcast_exact::<PyBytes>(vm)
.is_ok_and(|v| v.len() == 1)
|| value
.clone()
.to_owned()
.downcast_exact::<PyBytes>(vm)
.is_ok_and(|v| v.len() == 1)
|| value
.clone()
.to_owned()
.downcast_exact::<PyInt>(vm)
.map_or(Ok(false), |v| {
let n = v.as_bigint().to_i64();
@@ -69,7 +71,7 @@ fn set_primitive(_type_: &str, value: &PyObjectRef, vm: &VirtualMachine) -> PyRe
}
})?
{
Ok(value.clone())
Ok(value.to_owned())
} else {
Err(vm.new_type_error("one character bytes, bytearray or integer expected"))
}
@@ -77,7 +79,7 @@ fn set_primitive(_type_: &str, value: &PyObjectRef, vm: &VirtualMachine) -> PyRe
"u" => {
if let Ok(b) = value.str(vm).map(|v| v.to_string().chars().count() == 1) {
if b {
Ok(value.clone())
Ok(value.to_owned())
} else {
Err(vm.new_type_error("one character unicode string expected"))
}
@@ -89,8 +91,8 @@ fn set_primitive(_type_: &str, value: &PyObjectRef, vm: &VirtualMachine) -> PyRe
}
}
"b" | "h" | "H" | "i" | "I" | "l" | "q" | "L" | "Q" => {
if value.clone().downcast_exact::<PyInt>(vm).is_ok() {
Ok(value.clone())
if value.to_owned().downcast_exact::<PyInt>(vm).is_ok() {
Ok(value.to_owned())
} else {
Err(vm.new_type_error(format!(
"an integer is required (got type {})",
@@ -100,30 +102,30 @@ fn set_primitive(_type_: &str, value: &PyObjectRef, vm: &VirtualMachine) -> PyRe
}
"f" | "d" | "g" => {
// float allows int
if value.clone().downcast_exact::<PyFloat>(vm).is_ok()
|| value.clone().downcast_exact::<PyInt>(vm).is_ok()
if value.to_owned().downcast_exact::<PyFloat>(vm).is_ok()
|| value.to_owned().downcast_exact::<PyInt>(vm).is_ok()
{
Ok(value.clone())
Ok(value.to_owned())
} else {
Err(vm.new_type_error(format!("must be real number, not {}", value.class().name())))
}
}
"?" => Ok(PyObjectRef::from(
vm.ctx.new_bool(value.clone().try_to_bool(vm)?),
vm.ctx.new_bool(value.to_owned().try_to_bool(vm)?),
)),
"B" => {
if value.clone().downcast_exact::<PyInt>(vm).is_ok() {
if value.to_owned().downcast_exact::<PyInt>(vm).is_ok() {
// Store as-is, conversion to unsigned happens in the getter
Ok(value.clone())
Ok(value.to_owned())
} else {
Err(vm.new_type_error(format!("int expected instead of {}", value.class().name())))
}
}
"z" => {
if value.clone().downcast_exact::<PyInt>(vm).is_ok()
|| value.clone().downcast_exact::<PyBytes>(vm).is_ok()
if value.to_owned().downcast_exact::<PyInt>(vm).is_ok()
|| value.to_owned().downcast_exact::<PyBytes>(vm).is_ok()
{
Ok(value.clone())
Ok(value.to_owned())
} else {
Err(vm.new_type_error(format!(
"bytes or integer address expected instead of {} instance",
@@ -132,8 +134,8 @@ fn set_primitive(_type_: &str, value: &PyObjectRef, vm: &VirtualMachine) -> PyRe
}
}
"Z" => {
if value.clone().downcast_exact::<PyStr>(vm).is_ok() {
Ok(value.clone())
if value.to_owned().downcast_exact::<PyStr>(vm).is_ok() {
Ok(value.to_owned())
} else {
Err(vm.new_type_error(format!(
"unicode string or integer address expected instead of {} instance",
@@ -143,10 +145,10 @@ fn set_primitive(_type_: &str, value: &PyObjectRef, vm: &VirtualMachine) -> PyRe
}
_ => {
// "P"
if value.clone().downcast_exact::<PyInt>(vm).is_ok()
|| value.clone().downcast_exact::<PyNone>(vm).is_ok()
if value.to_owned().downcast_exact::<PyInt>(vm).is_ok()
|| value.to_owned().downcast_exact::<PyNone>(vm).is_ok()
{
Ok(value.clone())
Ok(value.to_owned())
} else {
Err(vm.new_type_error("cannot be converted to pointer"))
}
@@ -437,7 +439,7 @@ impl Debug for PyCSimple {
fn value_to_bytes_endian(
_type_: &str,
value: &PyObjectRef,
value: &PyObject,
swapped: bool,
vm: &VirtualMachine,
) -> Vec<u8> {
@@ -598,7 +600,7 @@ fn value_to_bytes_endian(
}
"?" => {
// c_bool (1 byte)
if let Ok(b) = value.clone().try_to_bool(vm) {
if let Ok(b) = value.to_owned().try_to_bool(vm) {
return vec![if b { 1 } else { 0 }];
}
vec![0]
+2 -2
View File
@@ -1,7 +1,7 @@
use crate::builtins::PyType;
use crate::function::PySetterValue;
use crate::types::{GetDescriptor, Representable};
use crate::{AsObject, Py, PyObjectRef, PyResult, VirtualMachine};
use crate::{AsObject, Py, PyObject, PyObjectRef, PyResult, VirtualMachine};
use num_traits::ToPrimitive;
use super::structure::PyCStructure;
@@ -152,7 +152,7 @@ impl PyCField {
}
/// Convert a Python value to bytes
fn value_to_bytes(value: &PyObjectRef, size: usize, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
fn value_to_bytes(value: &PyObject, size: usize, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
if let Ok(int_val) = value.try_int(vm) {
let i = int_val.as_bigint();
match size {
+3 -3
View File
@@ -7,7 +7,7 @@ use crate::function::FuncArgs;
use crate::protocol::{BufferDescriptor, BufferMethods, PyBuffer, PyNumberMethods};
use crate::stdlib::ctypes::_ctypes::get_size;
use crate::types::{AsBuffer, AsNumber, Constructor};
use crate::{AsObject, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine};
use crate::{AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine};
use indexmap::IndexMap;
use num_traits::ToPrimitive;
use rustpython_common::lock::PyRwLock;
@@ -109,7 +109,7 @@ impl PyCStructType {
}
/// Get the size of a ctypes type
fn get_field_size(field_type: &PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
fn get_field_size(field_type: &PyObject, vm: &VirtualMachine) -> PyResult<usize> {
// Try to get _type_ attribute for simple types
if let Some(size) = field_type
.get_attr("_type_", vm)
@@ -139,7 +139,7 @@ impl PyCStructType {
}
/// Get the alignment of a ctypes type
fn get_field_align(field_type: &PyObjectRef, vm: &VirtualMachine) -> usize {
fn get_field_align(field_type: &PyObject, vm: &VirtualMachine) -> usize {
// Try to get _type_ attribute for simple types
if let Some(align) = field_type
.get_attr("_type_", vm)
+2 -2
View File
@@ -7,7 +7,7 @@ use crate::function::FuncArgs;
use crate::protocol::{BufferDescriptor, BufferMethods, PyBuffer as ProtocolPyBuffer};
use crate::stdlib::ctypes::_ctypes::get_size;
use crate::types::{AsBuffer, Constructor};
use crate::{AsObject, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine};
use crate::{AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine};
use num_traits::ToPrimitive;
use rustpython_common::lock::PyRwLock;
@@ -90,7 +90,7 @@ impl PyCUnionType {
Ok(())
}
fn get_field_size(field_type: &PyObjectRef, vm: &VirtualMachine) -> PyResult<usize> {
fn get_field_size(field_type: &PyObject, vm: &VirtualMachine) -> PyResult<usize> {
if let Some(size) = field_type
.get_attr("_type_", vm)
.ok()
+4 -4
View File
@@ -44,7 +44,7 @@ fn caller(vm: &VirtualMachine) -> Option<PyObjectRef> {
/// Set __module__ attribute for an object based on the caller's module.
/// This follows CPython's behavior for TypeVar and similar objects.
fn set_module_from_caller(obj: &PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
fn set_module_from_caller(obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> {
// Note: CPython gets module from frame->f_funcobj, but RustPython's Frame
// architecture is different - we use globals['__name__'] instead
if let Some(module_name) = caller(vm) {
@@ -1006,15 +1006,15 @@ pub fn set_typeparam_default(
) -> PyResult {
// Inner function to handle common pattern of setting evaluate_default
fn try_set_default<T>(
obj: &PyObjectRef,
evaluate_default: &PyObjectRef,
obj: &PyObject,
evaluate_default: &PyObject,
get_field: impl FnOnce(&T) -> &PyMutex<PyObjectRef>,
) -> bool
where
T: PyPayload,
{
if let Some(typed_obj) = obj.downcast_ref::<T>() {
*get_field(typed_obj).lock() = evaluate_default.clone();
*get_field(typed_obj).lock() = evaluate_default.to_owned();
true
} else {
false
+4 -4
View File
@@ -2,9 +2,9 @@
//! This is used during tracebacks.
use crate::{
AsObject, Py, PyObjectRef, VirtualMachine,
AsObject, Py, PyObject, PyObjectRef, VirtualMachine,
builtins::{PyStr, PyStrRef},
exceptions::types::PyBaseExceptionRef,
exceptions::types::PyBaseException,
sliceable::SliceableSequenceOp,
};
use rustpython_common::str::levenshtein::{MOVE_COST, levenshtein_distance};
@@ -14,7 +14,7 @@ const MAX_CANDIDATE_ITEMS: usize = 750;
pub fn calculate_suggestions<'a>(
dir_iter: impl ExactSizeIterator<Item = &'a PyObjectRef>,
name: &PyObjectRef,
name: &PyObject,
) -> Option<PyStrRef> {
if dir_iter.len() >= MAX_CANDIDATE_ITEMS {
return None;
@@ -47,7 +47,7 @@ pub fn calculate_suggestions<'a>(
suggestion.map(|r| r.to_owned())
}
pub fn offer_suggestions(exc: &PyBaseExceptionRef, vm: &VirtualMachine) -> Option<PyStrRef> {
pub fn offer_suggestions(exc: &Py<PyBaseException>, vm: &VirtualMachine) -> Option<PyStrRef> {
if exc.class().is(vm.ctx.exceptions.attribute_error) {
let name = exc.as_object().get_attr("name", vm).unwrap();
let obj = exc.as_object().get_attr("obj", vm).unwrap();
+3 -3
View File
@@ -62,9 +62,9 @@ macro_rules! declare_const_name {
}
impl ConstName {
unsafe fn new(pool: &StringPool, typ: &PyTypeRef) -> Self {
unsafe fn new(pool: &StringPool, typ: &Py<PyType>) -> Self {
Self {
$($name: unsafe { pool.intern(declare_const_name!(@string $name $($s)?), typ.clone()) },)*
$($name: unsafe { pool.intern(declare_const_name!(@string $name $($s)?), typ.to_owned()) },)*
}
}
}
@@ -317,7 +317,7 @@ impl Context {
);
let string_pool = StringPool::default();
let names = unsafe { ConstName::new(&string_pool, &types.str_type.to_owned()) };
let names = unsafe { ConstName::new(&string_pool, types.str_type) };
let slot_new_wrapper = PyMethodDef::new_const(
names.__new__.as_str(),
+3 -2
View File
@@ -23,6 +23,7 @@ use crate::{
codecs::CodecsRegistry,
common::{hash::HashSecret, lock::PyMutex, rc::PyRc},
convert::ToPyObject,
exceptions::types::PyBaseException,
frame::{ExecutionResult, Frame, FrameRef},
frozen::FrozenModule,
function::{ArgMapping, FuncArgs, PySetterValue},
@@ -728,7 +729,7 @@ impl VirtualMachine {
pub fn set_attribute_error_context(
&self,
exc: &PyBaseExceptionRef,
exc: &Py<PyBaseException>,
obj: PyObjectRef,
name: PyStrRef,
) {
@@ -814,7 +815,7 @@ impl VirtualMachine {
drop(prev);
}
pub(crate) fn contextualize_exception(&self, exception: &PyBaseExceptionRef) {
pub(crate) fn contextualize_exception(&self, exception: &Py<PyBaseException>) {
if let Some(context_exc) = self.topmost_exception()
&& !context_exc.is(exception)
{
+2 -2
View File
@@ -1,5 +1,5 @@
use crate::{
AsObject, Context, Py, PyObjectRef, PyResult, VirtualMachine,
AsObject, Context, Py, PyObject, PyObjectRef, PyResult, VirtualMachine,
builtins::{
PyDictRef, PyListRef, PyStr, PyStrInterned, PyStrRef, PyTuple, PyTupleRef, PyTypeRef,
},
@@ -38,7 +38,7 @@ impl WarningsState {
}
}
fn check_matched(obj: &PyObjectRef, arg: &PyObjectRef, vm: &VirtualMachine) -> PyResult<bool> {
fn check_matched(obj: &PyObject, arg: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
if obj.class().is(vm.ctx.types.none_type) {
return Ok(true);
}
+3 -3
View File
@@ -4,8 +4,8 @@ use crate::js_module;
use crate::vm_class::{WASMVirtualMachine, stored_vm_from_wasm};
use js_sys::{Array, ArrayBuffer, Object, Promise, Reflect, SyntaxError, Uint8Array};
use rustpython_vm::{
AsObject, PyObjectRef, PyPayload, PyResult, TryFromBorrowedObject, VirtualMachine,
builtins::PyBaseExceptionRef,
AsObject, Py, PyObjectRef, PyPayload, PyResult, TryFromBorrowedObject, VirtualMachine,
builtins::{PyBaseException, PyBaseExceptionRef},
compiler::{CompileError, ParseError, parser::LexicalErrorType, parser::ParseErrorType},
exceptions,
function::{ArgBytesLike, FuncArgs},
@@ -32,7 +32,7 @@ extern "C" {
fn new(info: JsValue) -> PyError;
}
pub fn py_err_to_js_err(vm: &VirtualMachine, py_err: &PyBaseExceptionRef) -> JsValue {
pub fn py_err_to_js_err(vm: &VirtualMachine, py_err: &Py<PyBaseException>) -> JsValue {
let js_err = vm.try_class("_js", "JSError").ok();
let js_arg = if js_err.is_some_and(|js_err| py_err.fast_isinstance(&js_err)) {
py_err.get_arg(0)
+1 -2
View File
@@ -612,8 +612,7 @@ mod _js {
fn js_error(vm: &VirtualMachine) -> PyTypeRef {
let ctx = &vm.ctx;
let js_error = PyRef::leak(
PyType::new_simple_heap("JSError", &vm.ctx.exceptions.exception_type.to_owned(), ctx)
.unwrap(),
PyType::new_simple_heap("JSError", vm.ctx.exceptions.exception_type, ctx).unwrap(),
);
extend_class!(ctx, js_error, {
"value" => ctx.new_readonly_getset("value", js_error, |exc: PyBaseExceptionRef| exc.get_arg(0)),