diff --git a/crates/capi/src/floatobject.rs b/crates/capi/src/floatobject.rs index ead09c219..f7b0d0be4 100644 --- a/crates/capi/src/floatobject.rs +++ b/crates/capi/src/floatobject.rs @@ -51,7 +51,7 @@ pub unsafe extern "C" fn PyFloat_FromString(obj: *mut PyObject) -> *mut PyObject with_vm(|vm| { let obj = NonNull::new(obj) .ok_or_else(|| vm.new_type_error("float() argument must be a string or a number"))?; - let obj = unsafe { obj.as_ref() }.to_owned(); + let obj = unsafe { obj.as_ref() }; let float = rustpython_vm::builtins::parse_float_from_string(obj, vm)?; Ok(vm.ctx.new_float(float)) }) diff --git a/crates/stdlib/src/_asyncio.rs b/crates/stdlib/src/_asyncio.rs index 9c60c0fb8..47509b64b 100644 --- a/crates/stdlib/src/_asyncio.rs +++ b/crates/stdlib/src/_asyncio.rs @@ -2045,7 +2045,7 @@ pub(crate) mod _asyncio { // Handle the result match step_result { Ok(result) => { - task_step_handle_result(zelf, result, vm)?; + task_step_handle_result(zelf, &result, vm)?; } Err(e) => { task_step_handle_exception(zelf, e, vm)?; @@ -2143,7 +2143,7 @@ pub(crate) mod _asyncio { match result { Ok(result) => { - task_step_handle_result(&task_ref, result, vm)?; + task_step_handle_result(&task_ref, &result, vm)?; } Err(e) => { task_step_handle_exception(&task_ref, e, vm)?; @@ -2155,7 +2155,7 @@ pub(crate) mod _asyncio { fn task_step_handle_result( task: &Py, - result: PyObjectRef, + result: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { // Check if task awaits on itself @@ -2172,7 +2172,7 @@ pub(crate) mod _asyncio { let blocking = vm .get_attribute_opt( - result.clone(), + result.to_owned(), vm.ctx.intern_str("_asyncio_future_blocking"), )? .and_then(|v| v.try_to_bool(vm).ok()) @@ -2188,17 +2188,17 @@ pub(crate) mod _asyncio { // Get the future's loop, similar to get_future_loop: // 1. If it's our native Future/Task, access fut_loop directly (check Task first) // 2. Otherwise try get_loop(), falling back to _loop on AttributeError - let fut_loop = if let Ok(task) = result.clone().downcast::() { + let fut_loop = if let Ok(task) = result.to_owned().downcast::() { task.base .fut_loop .read() .clone() .unwrap_or_else(|| vm.ctx.none()) - } else if let Ok(fut) = result.clone().downcast::() { + } else if let Ok(fut) = result.to_owned().downcast::() { fut.fut_loop.read().clone().unwrap_or_else(|| vm.ctx.none()) } else { // Try get_loop(), fall back to _loop on AttributeError - match vm.call_method(&result, "get_loop", ()) { + match vm.call_method(result, "get_loop", ()) { Ok(loop_obj) => loop_obj, Err(e) if e.fast_isinstance(vm.ctx.exceptions.attribute_error) => { result.get_attr(vm.ctx.intern_str("_loop"), vm)? @@ -2227,14 +2227,14 @@ pub(crate) mod _asyncio { return Ok(()); } - *task.task_fut_waiter.write() = Some(result.clone()); + *task.task_fut_waiter.write() = Some(result.to_owned()); let task_obj: PyObjectRef = task.to_owned().into(); let wakeup_wrapper = TaskWakeupMethWrapper::new(task_obj.clone()).into_ref(&vm.ctx); - vm.call_method(&result, "add_done_callback", (wakeup_wrapper,))?; + vm.call_method(result, "add_done_callback", (wakeup_wrapper,))?; // Track awaited_by relationship for introspection - future_add_to_awaited_by(result.clone(), task_obj, vm)?; + future_add_to_awaited_by(result.to_owned(), task_obj, vm)?; // If task_must_cancel is set, cancel the awaited future immediately // This propagates the cancellation through the future chain @@ -2248,12 +2248,12 @@ pub(crate) mod _asyncio { } else { FuncArgs::new(vec![], KwArgs::default()) }; - let cancel_result = vm.call_method(&result, "cancel", cancel_args)?; + let cancel_result = vm.call_method(result, "cancel", cancel_args)?; if cancel_result.try_to_bool(vm).unwrap_or(false) { task.task_must_cancel.store(false, Ordering::Relaxed); } } - } else if vm.is_none(&result) { + } else if vm.is_none(result) { let loop_obj = task.base.fut_loop.read().clone(); if let Some(loop_obj) = loop_obj { let task_obj: PyObjectRef = task.to_owned().into(); diff --git a/crates/stdlib/src/array.rs b/crates/stdlib/src/array.rs index cbd843808..dd5f761c5 100644 --- a/crates/stdlib/src/array.rs +++ b/crates/stdlib/src/array.rs @@ -19,7 +19,7 @@ pub mod array { builtins::{ PositionIterInternal, PyByteArray, PyBytes, PyBytesRef, PyDictRef, PyFloat, PyGenericAlias, PyInt, PyList, PyListRef, PyStr, PyStrRef, PyTupleRef, PyType, - PyTypeRef, PyUtf8StrRef, builtins_iter, locked_next, + PyTypeRef, PyUtf8Str, PyUtf8StrRef, builtins_iter, locked_next, }, class_or_notimplemented, convert::{ToPyObject, ToPyResult, TryFromBorrowedObject, TryFromObject}, @@ -1060,8 +1060,8 @@ pub mod array { } } - fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self.getitem_inner(&needle, vm) + fn __getitem__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + self.getitem_inner(needle, vm) } fn setitem_inner( @@ -1107,11 +1107,11 @@ pub mod array { fn __setitem__( zelf: &Py, - needle: PyObjectRef, + needle: &PyObject, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - Self::setitem_inner(zelf, &needle, value, vm) + Self::setitem_inner(zelf, needle, value, vm) } fn delitem_inner(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<()> { @@ -1121,11 +1121,11 @@ pub mod array { } } - fn __delitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.delitem_inner(&needle, vm) + fn __delitem__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + self.delitem_inner(needle, vm) } - fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { + fn __add__(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult> { if let Some(other) = other.downcast_ref::() { self.read() .add(&other.read(), vm) @@ -1140,10 +1140,10 @@ pub mod array { fn __iadd__( zelf: PyRef, - other: PyObjectRef, + other: &PyObject, vm: &VirtualMachine, ) -> PyResult> { - if zelf.is(&other) { + if zelf.is(other) { zelf.try_resizable(vm)?.imul(2, vm)?; } else if let Some(other) = other.downcast_ref::() { zelf.try_resizable(vm)?.iadd(&other.read(), vm)?; @@ -1241,7 +1241,7 @@ pub mod array { )) } - fn __contains__(&self, value: PyObjectRef, vm: &VirtualMachine) -> bool { + fn __contains__(&self, value: &PyObject, vm: &VirtualMachine) -> bool { let array = self.array.read(); for element in array .iter(vm) @@ -1421,7 +1421,7 @@ pub mod array { length: atomic_func!(|seq, _vm| Ok(PyArray::sequence_downcast(seq).__len__())), concat: atomic_func!(|seq, other, vm| { let zelf = PyArray::sequence_downcast(seq); - PyArray::__add__(zelf, other.to_owned(), vm).map(|x| x.into()) + PyArray::__add__(zelf, other, vm).map(|x| x.into()) }), repeat: atomic_func!(|seq, n, vm| { PyArray::sequence_downcast(seq) @@ -1445,11 +1445,11 @@ pub mod array { }), contains: atomic_func!(|seq, target, vm| { let zelf = PyArray::sequence_downcast(seq); - Ok(zelf.__contains__(target.to_owned(), vm)) + Ok(zelf.__contains__(target, vm)) }), inplace_concat: atomic_func!(|seq, other, vm| { let zelf = PyArray::sequence_downcast(seq).to_owned(); - PyArray::__iadd__(zelf, other.to_owned(), vm).map(|x| x.into()) + PyArray::__iadd__(zelf, other, vm).map(|x| x.into()) }), inplace_repeat: atomic_func!(|seq, n, vm| { let zelf = PyArray::sequence_downcast(seq).to_owned(); @@ -1498,7 +1498,7 @@ pub mod array { fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal .lock() - .set_state(state, |obj, pos| pos.min(obj.__len__()), vm) + .set_state(&state, |obj, pos| pos.min(obj.__len__()), vm) } #[pymethod] @@ -1682,7 +1682,7 @@ pub mod array { Ok(typ) } - fn check_type_code(spec: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult { + fn check_type_code(spec: &Py, vm: &VirtualMachine) -> PyResult { let spec = spec.as_str().chars().exactly_one().map_err(|_| { vm.new_type_error( "_array_reconstructor() argument 2 must be a unicode character, not str", @@ -1718,7 +1718,7 @@ pub mod array { #[pyfunction] fn _array_reconstructor(args: ReconstructorArgs, vm: &VirtualMachine) -> PyResult { let cls = check_array_type(args.arraytype, vm)?; - let mut array = check_type_code(args.typecode, vm)?; + let mut array = check_type_code(&args.typecode, vm)?; let format = args.mformat_code; let bytes = args.items.as_bytes(); if !bytes.len().is_multiple_of(format.item_size()) { diff --git a/crates/stdlib/src/csv.rs b/crates/stdlib/src/csv.rs index 6b12922f5..442d26444 100644 --- a/crates/stdlib/src/csv.rs +++ b/crates/stdlib/src/csv.rs @@ -1346,14 +1346,15 @@ mod _csv { self.dialect.clone() } - fn writerow_quoted_strings(&self, row: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn writerow_quoted_strings(&self, row: &PyObject, vm: &VirtualMachine) -> PyResult { let _state = self.state.lock(); - let row: ArgIterable = ArgIterable::try_from_object(vm, row.clone()).map_err(|_e| { - new_csv_error( - vm, - format!("'{}' object is not iterable", row.class().name()), - ) - })?; + let row: ArgIterable = + ArgIterable::try_from_object(vm, row.to_owned()).map_err(|_e| { + new_csv_error( + vm, + format!("'{}' object is not iterable", row.class().name()), + ) + })?; let fields = row.iter(vm)?.collect::>>()?; let single_field = fields.len() == 1; let mut output = Vec::new(); @@ -1396,15 +1397,16 @@ mod _csv { self.write.call((s,), vm) } - fn writerow_quote_none(&self, row: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn writerow_quote_none(&self, row: &PyObject, vm: &VirtualMachine) -> PyResult { let _state = self.state.lock(); - let row: ArgIterable = ArgIterable::try_from_object(vm, row.clone()).map_err(|_e| { - new_csv_error( - vm, - format!("'{}' object is not iterable", row.class().name()), - ) - })?; + let row: ArgIterable = + ArgIterable::try_from_object(vm, row.to_owned()).map_err(|_e| { + new_csv_error( + vm, + format!("'{}' object is not iterable", row.class().name()), + ) + })?; let fields = row.iter(vm)?.collect::>>()?; let single_field = fields.len() == 1; @@ -1443,15 +1445,16 @@ mod _csv { self.write.call((s,), vm) } - fn writerow_minimal(&self, row: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn writerow_minimal(&self, row: &PyObject, vm: &VirtualMachine) -> PyResult { let _state = self.state.lock(); - let row: ArgIterable = ArgIterable::try_from_object(vm, row.clone()).map_err(|_e| { - new_csv_error( - vm, - format!("'{}' object is not iterable", row.class().name()), - ) - })?; + let row: ArgIterable = + ArgIterable::try_from_object(vm, row.to_owned()).map_err(|_e| { + new_csv_error( + vm, + format!("'{}' object is not iterable", row.class().name()), + ) + })?; let fields = row.iter(vm)?.collect::>>()?; let single_field = fields.len() == 1; @@ -1495,11 +1498,11 @@ mod _csv { #[pymethod] fn writerow(&self, row: PyObjectRef, vm: &VirtualMachine) -> PyResult { match self.dialect.quoting { - QuoteStyle::None => return self.writerow_quote_none(row, vm), + QuoteStyle::None => return self.writerow_quote_none(&row, vm), QuoteStyle::Strings | QuoteStyle::Notnull => { - return self.writerow_quoted_strings(row, vm); + return self.writerow_quoted_strings(&row, vm); } - QuoteStyle::Minimal => return self.writerow_minimal(row, vm), + QuoteStyle::Minimal => return self.writerow_minimal(&row, vm), _ => {} } diff --git a/crates/stdlib/src/elementtree.rs b/crates/stdlib/src/elementtree.rs index d1f593a19..9f6efa5e0 100644 --- a/crates/stdlib/src/elementtree.rs +++ b/crates/stdlib/src/elementtree.rs @@ -1685,7 +1685,7 @@ pub(crate) mod _elementtree { fn set_events( &self, events_append: PyObjectRef, - events_to_report: PyObjectRef, + events_to_report: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { { @@ -1697,7 +1697,7 @@ pub(crate) mod _elementtree { st.end_ns_event = None; st.comment_event = None; st.pi_event = None; - if vm.is_none(&events_to_report) { + if vm.is_none(events_to_report) { st.end_event = Some(vm.ctx.new_str("end").into()); return Ok(()); } @@ -2061,7 +2061,7 @@ pub(crate) mod _elementtree { Ok(value) } - fn raise_expat_error(&self, err: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + fn raise_expat_error(&self, err: &PyObject, vm: &VirtualMachine) -> PyResult<()> { let message = err.str(vm)?; let code = err .get_attr("code", vm) @@ -2099,7 +2099,7 @@ pub(crate) mod _elementtree { if let Ok(error_type) = error_type.downcast::() && e.fast_isinstance(&error_type) { - self.raise_expat_error(e.into(), vm)?; + self.raise_expat_error(e.as_object(), vm)?; unreachable!() } Err(e) @@ -2207,7 +2207,7 @@ pub(crate) mod _elementtree { )); }; let append = events_queue.get_attr("append", vm)?; - builder.set_events(append, events_to_report.unwrap_or_none(vm), vm)?; + builder.set_events(append, &events_to_report.unwrap_or_none(vm), vm)?; // Comments and processing instructions are only reported once // asked for, so their handlers are installed lazily here. let this = zelf.as_object(); diff --git a/crates/stdlib/src/hashlib.rs b/crates/stdlib/src/hashlib.rs index a863c6fa3..591604b7b 100644 --- a/crates/stdlib/src/hashlib.rs +++ b/crates/stdlib/src/hashlib.rs @@ -827,7 +827,7 @@ pub(crate) mod _hashlib { Ok(new_xof_hasher("shake_256", data)) } - fn parse_unsigned_int(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn parse_unsigned_int(obj: &PyObject, vm: &VirtualMachine) -> PyResult { let value = obj.try_index(vm)?; if value.as_bigint().sign() == malachite_bigint::Sign::Minus { return Err(vm.new_value_error("Cannot convert negative int")); @@ -960,14 +960,14 @@ pub(crate) mod _hashlib { let leaf_size = match args.leaf_size.into_option() { Some(obj) => { - let value = parse_unsigned_int(obj, vm)?; + let value = parse_unsigned_int(&obj, vm)?; u32::try_from(value).map_err(|_| vm.new_overflow_error("leaf_size is too large"))? } None => 0, }; let node_offset = match args.node_offset.into_option() { Some(obj) => { - let value = parse_unsigned_int(obj, vm)?; + let value = parse_unsigned_int(&obj, vm)?; if value > max_node_offset { return Err(vm.new_overflow_error("node_offset is too large")); } diff --git a/crates/stdlib/src/json.rs b/crates/stdlib/src/json.rs index e2d1b7f86..3842e1ced 100644 --- a/crates/stdlib/src/json.rs +++ b/crates/stdlib/src/json.rs @@ -98,7 +98,7 @@ mod _json { pystr: PyStrRef, char_idx: usize, byte_idx: usize, - scan_once: PyObjectRef, + scan_once: &PyObject, vm: &VirtualMachine, ) -> PyResult { flame_guard!("JsonScanner::parse"); @@ -128,7 +128,7 @@ mod _json { // Parse object in Rust let mut memo = HashMap::new(); return self - .parse_object(pystr, char_idx + 1, byte_idx + 1, &scan_once, &mut memo, vm) + .parse_object(pystr, char_idx + 1, byte_idx + 1, scan_once, &mut memo, vm) .map(|(obj, end_char, _end_byte)| { PyIterReturn::Return(vm.new_tuple((obj, end_char)).into()) }); @@ -137,7 +137,7 @@ mod _json { // Parse array in Rust let mut memo = HashMap::new(); return self - .parse_array(pystr, char_idx + 1, byte_idx + 1, &scan_once, &mut memo, vm) + .parse_array(pystr, char_idx + 1, byte_idx + 1, scan_once, &mut memo, vm) .map(|(obj, end_char, _end_byte)| { PyIterReturn::Return(vm.new_tuple((obj, end_char)).into()) }); @@ -688,7 +688,7 @@ mod _json { } }; - zelf.parse(pystr, char_idx, byte_idx, zelf.to_owned().into(), vm) + zelf.parse(pystr, char_idx, byte_idx, zelf.as_object(), vm) .and_then(|x| x.to_pyresult(vm)) } } diff --git a/crates/stdlib/src/lzma.rs b/crates/stdlib/src/lzma.rs index e05306d86..bc44fde8d 100644 --- a/crates/stdlib/src/lzma.rs +++ b/crates/stdlib/src/lzma.rs @@ -181,7 +181,7 @@ mod _lzma { } fn parse_filter_chain( - filter_specs: PyObjectRef, + filter_specs: &PyObject, vm: &VirtualMachine, ) -> PyResult> { const LZMA_FILTERS_MAX: usize = 4; @@ -206,7 +206,7 @@ mod _lzma { vm: &VirtualMachine, ) -> PyResult>> { filters - .map(|filters| parse_filter_chain(filters, vm)) + .map(|filters| parse_filter_chain(&filters, vm)) .transpose() } diff --git a/crates/stdlib/src/mmap.rs b/crates/stdlib/src/mmap.rs index 6136e2d19..8fbd184fc 100644 --- a/crates/stdlib/src/mmap.rs +++ b/crates/stdlib/src/mmap.rs @@ -679,7 +679,7 @@ mod mmap { ass_item: atomic_func!(|seq, i, value, vm| { let zelf = PyMmap::sequence_downcast(seq); if let Some(value) = value { - PyMmap::setitem_by_index(zelf, i, value, vm) + PyMmap::setitem_by_index(zelf, i, &value, vm) } else { Err(vm .new_type_error("mmap object doesn't support item deletion".to_owned())) @@ -905,9 +905,9 @@ mod mmap { vm: &VirtualMachine, ) -> PyResult<()> { fn args( - dest: PyIntRef, - src: PyIntRef, - cnt: PyIntRef, + dest: &Py, + src: &Py, + cnt: &Py, size: usize, vm: &VirtualMachine, ) -> Option<(usize, usize, usize)> { @@ -927,7 +927,7 @@ mod mmap { } let size = self.__len__(); - let (dest, src, cnt) = args(dest, src, cnt, size, vm) + let (dest, src, cnt) = args(&dest, &src, &cnt, size, vm) .ok_or_else(|| vm.new_value_error("source, destination, or count out of range"))?; let dest_end = dest + cnt; @@ -1234,17 +1234,17 @@ mod mmap { Ok(()) } - fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self.getitem_inner(&needle, vm) + fn __getitem__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + self.getitem_inner(needle, vm) } fn __setitem__( zelf: &Py, - needle: PyObjectRef, + needle: &PyObject, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - Self::setitem_inner(zelf, &needle, value, vm) + Self::setitem_inner(zelf, needle, value, vm) } #[pymethod] @@ -1358,22 +1358,22 @@ mod mmap { vm: &VirtualMachine, ) -> PyResult<()> { match SequenceIndex::try_from_borrowed_object(vm, needle, "mmap")? { - SequenceIndex::Int(i) => Self::setitem_by_index(zelf, i, value, vm), - SequenceIndex::Slice(slice) => Self::setitem_by_slice(zelf, &slice, value, vm), + SequenceIndex::Int(i) => Self::setitem_by_index(zelf, i, &value, vm), + SequenceIndex::Slice(slice) => Self::setitem_by_slice(zelf, &slice, &value, vm), } } fn setitem_by_index( &self, i: isize, - value: PyObjectRef, + value: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { let i: usize = i .wrapped_at(self.__len__()) .ok_or_else(|| vm.new_index_error("mmap index out of range"))?; - let b = value_from_object(vm, &value)?; + let b = value_from_object(vm, value)?; self.try_writable(vm, |mmap| { mmap[i] = b; @@ -1385,12 +1385,12 @@ mod mmap { fn setitem_by_slice( &self, slice: &SaturatedSlice, - value: PyObjectRef, + value: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { let (range, step, slice_len) = slice.adjust_indices(self.__len__()); - let bytes = bytes_from_object(vm, &value)?; + let bytes = bytes_from_object(vm, value)?; if bytes.len() != slice_len { return Err(vm.new_index_error("mmap slice assignment is wrong size")); diff --git a/crates/stdlib/src/pickle.rs b/crates/stdlib/src/pickle.rs index d38ba9426..4eca3f9e2 100644 --- a/crates/stdlib/src/pickle.rs +++ b/crates/stdlib/src/pickle.rs @@ -244,7 +244,7 @@ mod _pickle { frame_end: Option, } - fn to_byte_vec(obj: PyObjectRef, what: &str, vm: &VirtualMachine) -> PyResult> { + fn to_byte_vec(obj: &PyObject, what: &str, vm: &VirtualMachine) -> PyResult> { obj.downcast_ref::() .map(|b| b.as_bytes().to_vec()) .ok_or_else(|| { @@ -287,7 +287,7 @@ mod _pickle { { match peek.call((PREFETCH,), vm) { Ok(data) => { - let data = to_byte_vec(data, "peek", vm)?; + let data = to_byte_vec(&data, "peek", vm)?; let len = data.len(); self.set_input(data, false); if n <= len { @@ -301,7 +301,8 @@ mod _pickle { } } let read = self.read.clone().expect("file input"); - let data = to_byte_vec(read.call((n,), vm)?, "read", vm)?; + let data = read.call((n,), vm)?; + let data = to_byte_vec(&data, "read", vm)?; let len = data.len(); self.set_input(data, true); Ok(len) @@ -363,7 +364,8 @@ mod _pickle { } self.skip_consumed(vm)?; let readline = self.readline.clone().expect("file input"); - let data = to_byte_vec(readline.call((), vm)?, "readline", vm)?; + let data = readline.call((), vm)?; + let data = to_byte_vec(&data, "readline", vm)?; let len = data.len(); self.set_input(data, true); if len == 0 || self.buf[len - 1] != b'\n' { @@ -1403,7 +1405,7 @@ mod _pickle { Some(BUILD) => { let state = pop!(); let inst = top!(); - load_build(inst, state, vm)?; + load_build(&inst, state, vm)?; } Some(EXT1) => { let code = st.read_n(1, vm)?[0] as i32; @@ -1528,8 +1530,8 @@ mod _pickle { cls.call(args, vm) } - fn load_build(inst: PyObjectRef, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - if let Some(setstate) = vm.get_attribute_opt(inst.clone(), "__setstate__")? { + fn load_build(inst: &PyObject, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + if let Some(setstate) = vm.get_attribute_opt(inst.to_owned(), "__setstate__")? { setstate.call((state,), vm)?; return Ok(()); } @@ -2029,7 +2031,7 @@ mod _pickle { impl PyPickler { #[pymethod] fn dump(zelf: &Py, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - dump_impl(zelf, obj, vm) + dump_impl(zelf, &obj, vm) } #[pymethod] @@ -2384,7 +2386,7 @@ mod _pickle { if data.as_bytes().is_empty() { let bytes_type: PyObjectRef = vm.ctx.types.bytes_type.to_owned().into(); return self.save_reduce( - bytes_type, + &bytes_type, vm.ctx.new_tuple(vec![]).into(), None, None, @@ -2402,7 +2404,7 @@ mod _pickle { vm.ctx.new_str("latin1").into(), ]); return self.save_reduce( - encode, + &encode, args.into(), None, None, @@ -2432,7 +2434,7 @@ mod _pickle { vm.ctx.new_tuple(vec![vm.ctx.new_bytes(data).into()]) }; return self.save_reduce( - bytearray_type, + &bytearray_type, args.into(), None, None, @@ -2784,7 +2786,7 @@ mod _pickle { let elements = vm.ctx.new_list(set.elements()); let set_type: PyObjectRef = vm.ctx.types.set_type.to_owned().into(); return self.save_reduce( - set_type, + &set_type, vm.ctx.new_tuple(vec![elements.into()]).into(), None, None, @@ -2819,7 +2821,7 @@ mod _pickle { let elements = vm.ctx.new_list(set.elements()); let frozenset_type: PyObjectRef = vm.ctx.types.frozenset_type.to_owned().into(); return self.save_reduce( - frozenset_type, + &frozenset_type, vm.ctx.new_tuple(vec![elements.into()]).into(), None, None, @@ -3022,7 +3024,7 @@ mod _pickle { items.get(i).filter(|o| !vm.is_none(o)).cloned() }; self.save_reduce( - items[0].clone(), + &items[0], items[1].clone(), opt(2), opt(3), @@ -3036,7 +3038,7 @@ mod _pickle { #[allow(clippy::too_many_arguments)] fn save_reduce( &mut self, - func: PyObjectRef, + func: &PyObject, args: PyObjectRef, state: Option, listitems: Option, @@ -3050,7 +3052,7 @@ mod _pickle { vm, format!( "first item of the tuple returned by __reduce__ must be callable, not {}", - obj_type_name(&func, vm) + obj_type_name(func, vm) ), )); } @@ -3101,7 +3103,7 @@ mod _pickle { let obj_name = |vm: &VirtualMachine| obj.map_or_else(String::new, |o| obj_type_name(o, vm)); let func_name = vm - .get_attribute_opt(func.clone(), "__name__")? + .get_attribute_opt(func.to_owned(), "__name__")? .and_then(|o| { o.downcast_ref::() .map(|s| s.to_string_lossy().into_owned()) @@ -3238,7 +3240,7 @@ mod _pickle { })?; self.write(&[NEWOBJ as u8]); } else { - self.save(&func, false, vm).map_err(|e| { + self.save(func, false, vm).map_err(|e| { add_note( e, format!("when serializing {} reconstructor", obj_name(vm)), @@ -3334,7 +3336,7 @@ mod _pickle { }; match singleton { Some(value) => self.save_reduce( - type_type, + &type_type, vm.ctx.new_tuple(vec![value]).into(), None, None, @@ -3699,7 +3701,7 @@ mod _pickle { } } - fn dump_impl(zelf: &Py, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + fn dump_impl(zelf: &Py, obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> { let Some(mut out) = zelf.out.try_lock() else { return Err(vm.new_runtime_error("Pickler.dump() called recursively")); }; @@ -3754,7 +3756,7 @@ mod _pickle { buffer_callback, copyreg: None, }; - ctx.save(&obj, false, vm)?; + ctx.save(obj, false, vm)?; ctx.write(&[STOP as u8]); out.commit_frame(); out.flush_to_file(vm)?; @@ -3800,7 +3802,7 @@ mod _pickle { config: PyRwLock::new(config), } .into_ref(&vm.ctx); - dump_impl(&pickler, args.obj, vm) + dump_impl(&pickler, &args.obj, vm) } #[derive(FromArgs)] @@ -3830,7 +3832,7 @@ mod _pickle { config: PyRwLock::new(config), } .into_ref(&vm.ctx); - dump_impl(&pickler, args.obj, vm)?; + dump_impl(&pickler, &args.obj, vm)?; let data = core::mem::take(&mut pickler.out.lock().buf); Ok(vm.ctx.new_bytes(data).into()) } diff --git a/crates/stdlib/src/posixsubprocess.rs b/crates/stdlib/src/posixsubprocess.rs index 080c06468..960bec9a1 100644 --- a/crates/stdlib/src/posixsubprocess.rs +++ b/crates/stdlib/src/posixsubprocess.rs @@ -4,7 +4,7 @@ use crate::vm::{ builtins::PyListRef, function::ArgSequence, ospath::OsPath, - {PyObjectRef, PyResult, TryFromObject, VirtualMachine}, + {PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine}, }; use rustpython_host_env::posix as host_posix; use std::{ @@ -202,7 +202,7 @@ struct RawUid(u32); #[derive(Copy, Clone)] struct RawGid(u32); -fn try_from_id(vm: &VirtualMachine, obj: PyObjectRef, typ_name: &str) -> PyResult { +fn try_from_id(vm: &VirtualMachine, obj: &PyObject, typ_name: &str) -> PyResult { use core::cmp::Ordering; let i = obj .try_to_ref::(vm) @@ -225,13 +225,13 @@ fn try_from_id(vm: &VirtualMachine, obj: PyObjectRef, typ_name: &str) -> PyResul impl TryFromObject for RawUid { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - try_from_id(vm, obj, "uid").map(Self) + try_from_id(vm, &obj, "uid").map(Self) } } impl TryFromObject for RawGid { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - try_from_id(vm, obj, "gid").map(Self) + try_from_id(vm, &obj, "gid").map(Self) } } diff --git a/crates/stdlib/src/resource.rs b/crates/stdlib/src/resource.rs index 20bdecfea..2a95f28db 100644 --- a/crates/stdlib/src/resource.rs +++ b/crates/stdlib/src/resource.rs @@ -5,8 +5,8 @@ pub(crate) use resource::module_def; #[pymodule] mod resource { use crate::vm::{ - PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, VirtualMachine, - builtins::PyIntRef, + Py, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, VirtualMachine, + builtins::{PyInt, PyIntRef}, convert::{ToPyException, ToPyObject}, types::PyStructSequence, }; @@ -161,7 +161,7 @@ mod resource { } } - fn py2rlim(obj: PyIntRef, vm: &VirtualMachine) -> PyResult { + fn py2rlim(obj: &Py, vm: &VirtualMachine) -> PyResult { let value = obj.try_to_primitive::(vm)?; if value.is_negative() { @@ -186,7 +186,7 @@ mod resource { #[pyfunction] fn getrlimit(resource: PyIntRef, vm: &VirtualMachine) -> PyResult { - let resource = py2rlim(resource, vm)?; + let resource = py2rlim(&resource, vm)?; if resource >= RLIM_NLIMITS as host_resource::rlim_t { return Err(vm.new_value_error("invalid resource specified")); @@ -198,7 +198,7 @@ mod resource { #[pyfunction] fn setrlimit(resource: PyIntRef, limits: Limits, vm: &VirtualMachine) -> PyResult<()> { - let resource = py2rlim(resource, vm)?; + let resource = py2rlim(&resource, vm)?; if resource >= RLIM_NLIMITS as host_resource::rlim_t { return Err(vm.new_value_error("invalid resource specified")); diff --git a/crates/stdlib/src/socket.rs b/crates/stdlib/src/socket.rs index 4749be889..c8f6af6af 100644 --- a/crates/stdlib/src/socket.rs +++ b/crates/stdlib/src/socket.rs @@ -14,7 +14,7 @@ mod _socket { #[cfg(all(unix, not(target_os = "redox")))] use crate::vm::convert::ToPyException; use crate::vm::{ - AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, + AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::{ PyBaseExceptionRef, PyListRef, PyModule, PyOSError, PyStrRef, PyTupleRef, PyTypeRef, PyUtf8StrRef, @@ -761,7 +761,7 @@ mod _socket { }; } - fn get_raw_sock(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn get_raw_sock(obj: &PyObject, vm: &VirtualMachine) -> PyResult { #[cfg(unix)] type CastFrom = core::ffi::c_long; #[cfg(windows)] @@ -1357,7 +1357,7 @@ mod _socket { type Args = SocketInitArgs; fn init(zelf: PyRef, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - Self::_init(zelf, args, vm).map_err(|e| e.into_pyexception(vm)) + Self::_init(&zelf, args, vm).map_err(|e| e.into_pyexception(vm)) } } @@ -1402,7 +1402,7 @@ mod _socket { )] impl PySocket { fn _init( - zelf: PyRef, + zelf: &Py, args: ::Args, vm: &VirtualMachine, ) -> Result<(), IoOrPyException> { @@ -1445,7 +1445,7 @@ mod _socket { } // Not bytes, treat as regular fileno - let fileno = get_raw_sock(fileno_obj, vm)?; + let fileno = get_raw_sock(&fileno_obj, vm)?; sock = sock_from_raw(fileno, vm)?; match sock.local_addr() { Ok(addr) if family == -1 => family = addr.family() as i32, @@ -1471,7 +1471,7 @@ mod _socket { #[cfg(not(windows))] let fileno = fileno .flatten() - .map(|obj| get_raw_sock(obj, vm)) + .map(|obj| get_raw_sock(&obj, vm)) .transpose()?; #[cfg(not(windows))] if let Some(fileno) = fileno { @@ -3075,7 +3075,7 @@ mod _socket { #[pyfunction] fn dup(x: PyObjectRef, vm: &VirtualMachine) -> Result { - let sock = get_raw_sock(x, vm)?; + let sock = get_raw_sock(&x, vm)?; let sock = core::mem::ManuallyDrop::new(sock_from_raw(sock, vm)?); let newsock = sock.try_clone()?; let fd = into_sock_fileno(newsock); @@ -3086,7 +3086,7 @@ mod _socket { #[pyfunction] fn close(x: PyObjectRef, vm: &VirtualMachine) -> Result<(), IoOrPyException> { - Ok(close_inner(get_raw_sock(x, vm)?)?) + Ok(close_inner(get_raw_sock(&x, vm)?)?) } fn close_inner(x: RawSocket) -> io::Result<()> { diff --git a/crates/stdlib/src/unicodedata.rs b/crates/stdlib/src/unicodedata.rs index 122957439..fd74e73d0 100644 --- a/crates/stdlib/src/unicodedata.rs +++ b/crates/stdlib/src/unicodedata.rs @@ -34,7 +34,7 @@ mod unicodedata { use super::{NormalizeFormArg, unicode_core}; use crate::vm::{ Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, - builtins::{PyModule, PyStrRef}, + builtins::{PyModule, PyStr, PyStrRef}, function::OptionalArg, }; use itertools::Itertools; @@ -81,7 +81,7 @@ mod unicodedata { } } - fn extract_char(&self, character: PyStrRef, vm: &VirtualMachine) -> PyResult { + fn extract_char(&self, character: &Py, vm: &VirtualMachine) -> PyResult { character .as_wtf8() .code_points() @@ -94,7 +94,7 @@ mod unicodedata { impl Ucd { #[pymethod] fn category(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> { - self.extract_char(chr, vm).map(|c| self.inner.category(c)) + self.extract_char(&chr, vm).map(|c| self.inner.category(c)) } #[pymethod] @@ -121,7 +121,7 @@ mod unicodedata { default: OptionalArg, vm: &VirtualMachine, ) -> PyResult { - if let Some(name) = self.extract_char(chr, vm)?.to_char().and_then(|ch| { + if let Some(name) = self.extract_char(&chr, vm)?.to_char().and_then(|ch| { self.inner .membership(ch) .then(|| unicode_core::character_name(ch)) @@ -134,13 +134,13 @@ mod unicodedata { #[pymethod] fn bidirectional(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> { - self.extract_char(chr, vm) + self.extract_char(&chr, vm) .map(|c| self.inner.bidirectional(c)) } #[pymethod] fn east_asian_width(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> { - self.extract_char(chr, vm) + self.extract_char(&chr, vm) .map(|c| self.inner.east_asian_width(c)) } @@ -156,17 +156,17 @@ mod unicodedata { #[pymethod] fn mirrored(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult { - self.extract_char(chr, vm).map(|c| self.inner.mirrored(c)) + self.extract_char(&chr, vm).map(|c| self.inner.mirrored(c)) } #[pymethod] fn combining(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult { - self.extract_char(chr, vm).map(|c| self.inner.combining(c)) + self.extract_char(&chr, vm).map(|c| self.inner.combining(c)) } #[pymethod] fn decomposition(&self, chr: PyStrRef, vm: &VirtualMachine) -> PyResult { - self.extract_char(chr, vm) + self.extract_char(&chr, vm) .map(|c| self.inner.decomposition(c)) } @@ -177,7 +177,7 @@ mod unicodedata { default: OptionalArg, vm: &VirtualMachine, ) -> PyResult> { - let ch = self.extract_char(chr, vm)?; + let ch = self.extract_char(&chr, vm)?; self.inner .digit(ch) .map(|value| vm.ctx.new_int(value).into()) @@ -193,7 +193,7 @@ mod unicodedata { default: OptionalArg, vm: &VirtualMachine, ) -> PyResult> { - let ch = self.extract_char(chr, vm)?; + let ch = self.extract_char(&chr, vm)?; self.inner .decimal(ch) .map(|value| vm.ctx.new_int(value).into()) @@ -209,7 +209,7 @@ mod unicodedata { default: OptionalArg, vm: &VirtualMachine, ) -> PyResult> { - let ch = self.extract_char(chr, vm)?; + let ch = self.extract_char(&chr, vm)?; self.inner .numeric(ch) .map(|value| vm.ctx.new_float(value).into()) diff --git a/crates/vm/src/anystr.rs b/crates/vm/src/anystr.rs index 4896f2789..20c2de260 100644 --- a/crates/vm/src/anystr.rs +++ b/crates/vm/src/anystr.rs @@ -4,8 +4,8 @@ use num_traits::{cast::ToPrimitive, sign::Signed}; use rustpython_unicode::case; use crate::{ - AsObject, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, - builtins::{PyIntRef, PyTuple}, + AsObject, Py, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, + builtins::{PyInt, PyIntRef, PyTuple}, convert::TryFromBorrowedObject, function::OptionalOption, }; @@ -75,7 +75,7 @@ impl StartsEndsWithArgs { } } -fn saturate_to_isize(py_int: PyIntRef) -> isize { +fn saturate_to_isize(py_int: &Py) -> isize { let big = py_int.as_bigint(); big.to_isize().unwrap_or_else(|| { if big.is_negative() { @@ -92,8 +92,8 @@ pub(crate) fn adjust_indices( end: Option, len: usize, ) -> Range { - let mut start = start.map_or(0, saturate_to_isize); - let mut end = end.map_or(len as isize, saturate_to_isize); + let mut start = start.as_deref().map_or(0, saturate_to_isize); + let mut end = end.as_deref().map_or(len as isize, saturate_to_isize); if end > len as isize { end = len as isize; } else if end < 0 { diff --git a/crates/vm/src/buffer.rs b/crates/vm/src/buffer.rs index 05816455c..dd48d0065 100644 --- a/crates/vm/src/buffer.rs +++ b/crates/vm/src/buffer.rs @@ -1,5 +1,5 @@ use crate::{ - AsObject, Py, PyObjectRef, PyResult, TryFromObject, VirtualMachine, + AsObject, Py, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, builtins::{PyBaseExceptionRef, PyBytesRef, PyTuple, PyTupleRef, PyType, PyTypeRef}, common::{static_cell, str::wchar_t}, convert::ToPyObject, @@ -663,7 +663,7 @@ macro_rules! make_pack_prim_int { arg: PyObjectRef, data: &mut [u8], ) -> Result<(), PackError> { - let i: $T = get_int_or_index(vm, code, arg)?; + let i: $T = get_int_or_index(vm, code, &arg)?; i.pack_int::(data); Ok(()) } @@ -679,7 +679,7 @@ macro_rules! make_pack_prim_int { fn get_int_or_index( vm: &VirtualMachine, code: FormatType, - arg: PyObjectRef, + arg: &PyObject, ) -> Result where T: PrimInt + fmt::Display + for<'a> TryFrom<&'a BigInt>, diff --git a/crates/vm/src/builtins/bool.rs b/crates/vm/src/builtins/bool.rs index 1d6ebe55f..28d598ebf 100644 --- a/crates/vm/src/builtins/bool.rs +++ b/crates/vm/src/builtins/bool.rs @@ -123,11 +123,11 @@ impl PyBool { } impl PyBool { - pub(crate) fn __or__(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { + pub(crate) fn __or__(lhs: &PyObject, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if lhs.fast_isinstance(vm.ctx.types.bool_type) && rhs.fast_isinstance(vm.ctx.types.bool_type) { - let lhs = get_value(&lhs); + let lhs = get_value(lhs); let rhs = get_value(&rhs); (lhs || rhs).to_pyobject(vm) } else if let Some(lhs) = lhs.downcast_ref::() { @@ -137,11 +137,11 @@ impl PyBool { } } - pub(crate) fn __and__(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { + pub(crate) fn __and__(lhs: &PyObject, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if lhs.fast_isinstance(vm.ctx.types.bool_type) && rhs.fast_isinstance(vm.ctx.types.bool_type) { - let lhs = get_value(&lhs); + let lhs = get_value(lhs); let rhs = get_value(&rhs); (lhs && rhs).to_pyobject(vm) } else if let Some(lhs) = lhs.downcast_ref::() { @@ -151,11 +151,11 @@ impl PyBool { } } - pub(crate) fn __xor__(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { + pub(crate) fn __xor__(lhs: &PyObject, rhs: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { if lhs.fast_isinstance(vm.ctx.types.bool_type) && rhs.fast_isinstance(vm.ctx.types.bool_type) { - let lhs = get_value(&lhs); + let lhs = get_value(lhs); let rhs = get_value(&rhs); (lhs ^ rhs).to_pyobject(vm) } else if let Some(lhs) = lhs.downcast_ref::() { @@ -169,9 +169,9 @@ impl PyBool { impl AsNumber for PyBool { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { - and: Some(|a, b, vm| PyBool::__and__(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)), - xor: Some(|a, b, vm| PyBool::__xor__(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)), - or: Some(|a, b, vm| PyBool::__or__(a.to_owned(), b.to_owned(), vm).to_pyresult(vm)), + and: Some(|a, b, vm| PyBool::__and__(a, b.to_owned(), vm).to_pyresult(vm)), + xor: Some(|a, b, vm| PyBool::__xor__(a, b.to_owned(), vm).to_pyresult(vm)), + or: Some(|a, b, vm| PyBool::__or__(a, b.to_owned(), vm).to_pyresult(vm)), ..PyInt::AS_NUMBER }; &AS_NUMBER diff --git a/crates/vm/src/builtins/bytearray.rs b/crates/vm/src/builtins/bytearray.rs index a71be4650..19dc46deb 100644 --- a/crates/vm/src/builtins/bytearray.rs +++ b/crates/vm/src/builtins/bytearray.rs @@ -96,8 +96,8 @@ impl PyByteArray { self.inner().mul(value, vm).map(|x| x.into()) } - fn _setitem_by_index(&self, i: isize, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - let value = value_from_object(vm, &value)?; + fn _setitem_by_index(&self, i: isize, value: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + let value = value_from_object(vm, value)?; self.borrow_buf_mut().setitem_by_index(vm, i, value) } @@ -108,7 +108,7 @@ impl PyByteArray { vm: &VirtualMachine, ) -> PyResult<()> { match SequenceIndex::try_from_borrowed_object(vm, needle, "bytearray")? { - SequenceIndex::Int(i) => zelf._setitem_by_index(i, value, vm), + SequenceIndex::Int(i) => zelf._setitem_by_index(i, &value, vm), SequenceIndex::Slice(slice) => { let items = if zelf.is(&value) { zelf.borrow_buf().to_vec() @@ -243,12 +243,12 @@ impl PyByteArray { Ok(zelf) } - fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self._getitem(&needle, vm) + fn __getitem__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + self._getitem(needle, vm) } - pub fn __delitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self._delitem(&needle, vm) + pub fn __delitem__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + self._delitem(needle, vm) } #[pystaticmethod] @@ -326,7 +326,7 @@ impl PyByteArray { #[pyclassmethod] fn fromhex(cls: PyTypeRef, string: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let bytes = PyBytesInner::fromhex_object(string, vm)?; + let bytes = PyBytesInner::fromhex_object(&string, vm)?; let bytes = vm.ctx.new_bytes(bytes); let args = vec![bytes.into()].into(); PyType::call(&cls, args, vm) @@ -571,11 +571,11 @@ impl PyByteArray { impl Py { fn __setitem__( &self, - needle: PyObjectRef, + needle: &PyObject, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - PyByteArray::_setitem(self, &needle, value, vm) + PyByteArray::_setitem(self, needle, value, vm) } #[pymethod] @@ -798,14 +798,14 @@ impl AsMapping for PyByteArray { PyByteArray::mapping_downcast(mapping).__len__() )), subscript: atomic_func!(|mapping, needle, vm| { - PyByteArray::mapping_downcast(mapping).__getitem__(needle.to_owned(), vm) + PyByteArray::mapping_downcast(mapping).__getitem__(needle, vm) }), ass_subscript: atomic_func!(|mapping, needle, value, vm| { let zelf = PyByteArray::mapping_downcast(mapping); if let Some(value) = value { - zelf.__setitem__(needle.to_owned(), value, vm) + zelf.__setitem__(needle, value, vm) } else { - zelf.__delitem__(needle.to_owned(), vm) + zelf.__delitem__(needle, vm) } }), }; @@ -837,7 +837,7 @@ impl AsSequence for PyByteArray { ass_item: atomic_func!(|seq, i, value, vm| { let zelf = PyByteArray::sequence_downcast(seq); if let Some(value) = value { - zelf._setitem_by_index(i, value, vm) + zelf._setitem_by_index(i, &value, vm) } else { zelf.borrow_buf_mut().delitem_by_index(vm, i) } @@ -928,7 +928,7 @@ impl PyByteArrayIterator { fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal .lock() - .set_state(state, |obj, pos| pos.min(obj.__len__()), vm) + .set_state(&state, |obj, pos| pos.min(obj.__len__()), vm) } } diff --git a/crates/vm/src/builtins/bytes.rs b/crates/vm/src/builtins/bytes.rs index e7d41c050..11e6956ad 100644 --- a/crates/vm/src/builtins/bytes.rs +++ b/crates/vm/src/builtins/bytes.rs @@ -254,8 +254,8 @@ impl PyBytes { PyBytesInner::maketrans(frm, to, vm) } - fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self._getitem(&needle, vm) + fn __getitem__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + self._getitem(needle, vm) } #[pymethod] @@ -330,7 +330,7 @@ impl PyBytes { #[pyclassmethod] fn fromhex(cls: PyTypeRef, string: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let bytes = PyBytesInner::fromhex_object(string, vm)?; + let bytes = PyBytesInner::fromhex_object(&string, vm)?; let bytes = vm.ctx.new_bytes(bytes).into(); PyType::call(&cls, vec![bytes].into(), vm) } @@ -787,7 +787,7 @@ impl PyBytesIterator { fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal .lock() - .set_state(state, |obj, pos| pos.min(obj.len()), vm) + .set_state(&state, |obj, pos| pos.min(obj.len()), vm) } } diff --git a/crates/vm/src/builtins/classmethod.rs b/crates/vm/src/builtins/classmethod.rs index 29ab45608..c0f6d5f78 100644 --- a/crates/vm/src/builtins/classmethod.rs +++ b/crates/vm/src/builtins/classmethod.rs @@ -120,9 +120,9 @@ impl PyClassMethod { #[pygetset] fn __annotations__(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let callable = zelf.callable.lock().clone(); + let callable = zelf.callable.lock(); descriptor_get_wrapped_attribute( - callable, + &callable, zelf.as_object(), identifier!(vm.ctx, __annotations__), vm, @@ -146,9 +146,9 @@ impl PyClassMethod { #[pygetset] fn __annotate__(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let callable = zelf.callable.lock().clone(); + let callable = zelf.callable.lock(); descriptor_get_wrapped_attribute( - callable, + &callable, zelf.as_object(), identifier!(vm.ctx, __annotate__), vm, @@ -247,7 +247,7 @@ pub(crate) fn functools_wraps( } pub(crate) fn descriptor_get_wrapped_attribute( - wrapped: PyObjectRef, + wrapped: &PyObject, obj: &PyObject, name: &'static PyStrInterned, vm: &VirtualMachine, diff --git a/crates/vm/src/builtins/descriptor.rs b/crates/vm/src/builtins/descriptor.rs index e848353e8..50b35151d 100644 --- a/crates/vm/src/builtins/descriptor.rs +++ b/crates/vm/src/builtins/descriptor.rs @@ -210,7 +210,7 @@ impl PyMemberDef { fn get(&self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { match self.getter { MemberGetter::Getter(getter) => (getter)(vm, obj), - MemberGetter::Offset(offset) => get_slot_from_object(obj, offset, self, vm), + MemberGetter::Offset(offset) => get_slot_from_object(&obj, offset, self, vm), } } @@ -225,7 +225,7 @@ impl PyMemberDef { Some(setter) => (setter)(vm, obj, value), None => Err(vm.new_attribute_error("readonly attribute")), }, - MemberSetter::Offset(offset) => set_slot_at_object(obj, offset, self, value, vm), + MemberSetter::Offset(offset) => set_slot_at_object(&obj, offset, self, value, vm), } } } @@ -338,7 +338,7 @@ impl PyMemberDescriptor { // PyMember_GetOne fn get_slot_from_object( - obj: PyObjectRef, + obj: &PyObject, offset: usize, member: &PyMemberDef, vm: &VirtualMachine, @@ -362,7 +362,7 @@ fn get_slot_from_object( // PyMember_SetOne fn set_slot_at_object( - obj: PyObjectRef, + obj: &PyObject, offset: usize, member: &PyMemberDef, value: PySetterValue, @@ -779,7 +779,7 @@ impl SlotFunc { // Buffer protocol Self::GetBuffer(func) => { let (flags_obj,): (PyObjectRef,) = args.bind(vm)?; - let buffer = func(&obj, parse_buffer_flags(flags_obj, vm)?, vm)?; + let buffer = func(&obj, parse_buffer_flags(&flags_obj, vm)?, vm)?; crate::builtins::PyMemoryView::from_buffer(buffer, vm) .map(|mv| mv.into_pyobject(vm)) } @@ -788,7 +788,7 @@ impl SlotFunc { let mv = mv_obj .downcast::() .map_err(|_| vm.new_type_error("expected a memoryview object"))?; - crate::builtins::memory::release_buffer_from_python(&obj, mv, vm)?; + crate::builtins::memory::release_buffer_from_python(&obj, &mv, vm)?; Ok(vm.ctx.none()) } } @@ -815,7 +815,7 @@ fn pow_args(args: FuncArgs, vm: &VirtualMachine) -> PyResult<(PyObjectRef, PyObj /// Parse the `flags` argument of `__buffer__`. wrap_buffer fn parse_buffer_flags( - arg: PyObjectRef, + arg: &PyObject, vm: &VirtualMachine, ) -> PyResult { use num_traits::ToPrimitive; diff --git a/crates/vm/src/builtins/dict.rs b/crates/vm/src/builtins/dict.rs index 168328015..c69594e99 100644 --- a/crates/vm/src/builtins/dict.rs +++ b/crates/vm/src/builtins/dict.rs @@ -142,7 +142,7 @@ impl PyDict { let casted: Result, _> = other.downcast_exact(vm); let other = match casted { Ok(dict_other) => { - return self.merge_dict(dict_other.into_pyref(), override_existing, vm); + return self.merge_dict(&dict_other, override_existing, vm); } Err(other) => other, }; @@ -271,13 +271,13 @@ impl PyDict { pub(crate) fn merge_dict( &self, - dict_other: PyDictRef, + dict_other: &Py, override_existing: bool, vm: &VirtualMachine, ) -> PyResult<()> { let dict = &self.entries; let dict_size = &dict_other.size(); - for (key, value) in &dict_other { + for (key, value) in dict_other { if !override_existing && dict.contains(vm, &*key)? { continue; } @@ -315,10 +315,10 @@ impl PyDict { pub fn get_or_insert( &self, vm: &VirtualMachine, - key: PyObjectRef, + key: &PyObject, default: impl FnOnce() -> PyObjectRef, ) -> PyResult { - self.entries.setdefault(vm, &*key, default) + self.entries.setdefault(vm, key, default) } pub fn from_attributes(attrs: PyAttributes, vm: &VirtualMachine) -> PyResult { @@ -402,7 +402,8 @@ impl PyDict { } } else { for key in iterable.iter(vm)? { - pydict.__setitem__(key?, value.clone(), vm)?; + let key = key?; + pydict.__setitem__(&key, value.clone(), vm)?; } } Ok(pydict.into_pyref().into()) @@ -425,12 +426,12 @@ impl PyDict { core::mem::size_of::() + self.entries.sizeof() } - fn __contains__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self.entries.contains(vm, &*key) + fn __contains__(&self, key: &PyObject, vm: &VirtualMachine) -> PyResult { + self.entries.contains(vm, key) } - fn __delitem__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.inner_delitem(&*key, vm) + fn __delitem__(&self, key: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + self.inner_delitem(key, vm) } #[pymethod] @@ -438,13 +439,8 @@ impl PyDict { self.entries.clear() } - fn __setitem__( - &self, - key: PyObjectRef, - value: PyObjectRef, - vm: &VirtualMachine, - ) -> PyResult<()> { - self.inner_setitem(&*key, value, vm) + fn __setitem__(&self, key: &PyObject, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + self.inner_setitem(key, value, vm) } #[pymethod] @@ -499,7 +495,7 @@ impl PyDict { let other_dict: Result = other.downcast(); if let Ok(other) = other_dict { let self_cp = self.copy(); - self_cp.merge_dict(other, true, vm)?; + self_cp.merge_dict(&other, true, vm)?; return Ok(self_cp.into_pyobject(vm)); } Ok(vm.ctx.not_implemented()) @@ -618,7 +614,7 @@ impl PyRef { let other_dict: Result = other.downcast(); if let Ok(other) = other_dict { let other_cp = other.copy(); - other_cp.merge_dict(self, true, vm)?; + other_cp.merge_dict(&self, true, vm)?; return Ok(other_cp.into_pyobject(vm)); } Ok(vm.ctx.not_implemented()) @@ -1550,8 +1546,8 @@ impl ViewSetOps for PyDictKeys {} ) )] impl PyDictKeys { - fn __contains__(zelf: PyObjectRef, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { - zelf.sequence_unchecked().contains(&key, vm) + fn __contains__(zelf: &PyObject, key: &PyObject, vm: &VirtualMachine) -> PyResult { + zelf.sequence_unchecked().contains(key, vm) } #[pygetset] @@ -1614,8 +1610,8 @@ impl ViewSetOps for PyDictItems {} ) )] impl PyDictItems { - fn __contains__(zelf: PyObjectRef, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - zelf.sequence_unchecked().contains(&needle, vm) + fn __contains__(zelf: &PyObject, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + zelf.sequence_unchecked().contains(needle, vm) } #[pygetset] fn mapping(zelf: PyRef) -> PyMappingProxy { @@ -1649,7 +1645,7 @@ impl AsSequence for PyDictItems { let zelf = PyDictItems::sequence_downcast(seq); let key = &needle[0]; - if !zelf.dict.__contains__(key.to_owned(), vm)? { + if !zelf.dict.__contains__(key, vm)? { return Ok(false); } let value = &needle[1]; diff --git a/crates/vm/src/builtins/enumerate.rs b/crates/vm/src/builtins/enumerate.rs index cf9fbcde5..0432ee87a 100644 --- a/crates/vm/src/builtins/enumerate.rs +++ b/crates/vm/src/builtins/enumerate.rs @@ -174,7 +174,7 @@ impl PyReverseSequenceIterator { #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.internal.lock().set_state(state, |_, pos| pos, vm) + self.internal.lock().set_state(&state, |_, pos| pos, vm) } #[pymethod] diff --git a/crates/vm/src/builtins/float.rs b/crates/vm/src/builtins/float.rs index b29e39b0a..8eadc0c04 100644 --- a/crates/vm/src/builtins/float.rs +++ b/crates/vm/src/builtins/float.rs @@ -199,7 +199,7 @@ impl Constructor for PyFloat { if let Some(f) = val.try_float_opt(vm) { f?.value } else { - float_from_string(val, vm)? + float_from_string(&val, vm)? } } }; @@ -207,7 +207,7 @@ impl Constructor for PyFloat { } } -pub fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult { +pub fn float_from_string(val: &PyObject, vm: &VirtualMachine) -> PyResult { let (bytearray, buffer, buffer_lock, mapped_string); let b = if let Some(s) = val.downcast_ref::() { mapped_string = crate::protocol::numeric_literal_from_str(s); @@ -217,7 +217,7 @@ pub fn float_from_string(val: PyObjectRef, vm: &VirtualMachine) -> PyResult } else if let Some(buf) = val.downcast_ref::() { bytearray = buf.borrow_buf(); &*bytearray - } else if let Ok(b) = ArgBytesLike::try_from_borrowed_object(vm, &val) { + } else if let Ok(b) = ArgBytesLike::try_from_borrowed_object(vm, val) { buffer = b; buffer_lock = buffer.borrow_buf(); &*buffer_lock diff --git a/crates/vm/src/builtins/frame_locals_proxy.rs b/crates/vm/src/builtins/frame_locals_proxy.rs index 00ff76ff4..888c6ec95 100644 --- a/crates/vm/src/builtins/frame_locals_proxy.rs +++ b/crates/vm/src/builtins/frame_locals_proxy.rs @@ -107,7 +107,7 @@ impl FrameLocalsProxy { value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - self.frame.framelocalsproxy_setitem(key, value, vm) + self.frame.framelocalsproxy_setitem(&key, value, vm) } fn __delitem__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { @@ -115,7 +115,7 @@ impl FrameLocalsProxy { } fn __contains__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self.frame.framelocalsproxy_contains(key, vm) + self.frame.framelocalsproxy_contains(&key, vm) } fn __len__(&self, vm: &VirtualMachine) -> PyResult { @@ -203,7 +203,7 @@ impl FrameLocalsProxy { .get_iter(vm)?; while let PyIterReturn::Return(key) = keys.next(vm)? { let value = other.get_item(&*key, vm)?; - self.frame.framelocalsproxy_setitem(key, value, vm)?; + self.frame.framelocalsproxy_setitem(&key, value, vm)?; } Ok(()) } @@ -215,11 +215,11 @@ impl FrameLocalsProxy { Ok(vm.ctx.new_list(keys).into()) } - fn __ior__(zelf: PyRef, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn __ior__(zelf: PyRef, other: &PyObject, vm: &VirtualMachine) -> PyResult { if other.downcast_ref::().is_none() && other.downcast_ref::().is_none() { return Ok(vm.ctx.not_implemented()); } - zelf.update_from(&other, vm)?; + zelf.update_from(other, vm)?; Ok(zelf.into()) } @@ -231,14 +231,14 @@ impl FrameLocalsProxy { if other.downcast_ref::().is_some() { // PyDict_Update reads a dict subclass's stored entries directly; // it does not dispatch to overridden mapping methods. - result.merge_dict(other.downcast().unwrap(), true, vm)?; + result.merge_dict(&other.downcast().unwrap(), true, vm)?; } else { result.merge_object(other, vm)?; } Ok(result.into()) } - fn __ror__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn __ror__(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult { let Some(other) = other.downcast_ref::() else { return Ok(vm.ctx.not_implemented()); }; @@ -298,7 +298,7 @@ impl AsNumber for FrameLocalsProxy { if let Some(proxy) = a.downcast_ref::() { proxy.__or__(b.to_owned(), vm) } else if let Some(proxy) = b.downcast_ref::() { - proxy.__ror__(a.to_owned(), vm) + proxy.__ror__(a, vm) } else { Ok(vm.ctx.not_implemented()) } @@ -308,7 +308,7 @@ impl AsNumber for FrameLocalsProxy { .to_owned() .downcast::() .map_err(|_| vm.new_type_error("expected FrameLocalsProxy"))?; - FrameLocalsProxy::__ior__(proxy, b.to_owned(), vm) + FrameLocalsProxy::__ior__(proxy, b, vm) }), ..PyNumberMethods::NOT_IMPLEMENTED }; diff --git a/crates/vm/src/builtins/genericalias.rs b/crates/vm/src/builtins/genericalias.rs index f9c566f53..7ea4c01a6 100644 --- a/crates/vm/src/builtins/genericalias.rs +++ b/crates/vm/src/builtins/genericalias.rs @@ -117,25 +117,25 @@ impl PyGenericAlias { } fn repr(&self, vm: &VirtualMachine) -> PyResult { - fn repr_item(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn repr_item(obj: &PyObject, vm: &VirtualMachine) -> PyResult { if obj.is(&vm.ctx.ellipsis) { return Ok("...".to_string()); } if vm - .get_attribute_opt(obj.clone(), identifier!(vm, __origin__))? + .get_attribute_opt(obj.to_owned(), identifier!(vm, __origin__))? .is_some() && vm - .get_attribute_opt(obj.clone(), identifier!(vm, __args__))? + .get_attribute_opt(obj.to_owned(), identifier!(vm, __args__))? .is_some() { return Ok(obj.repr(vm)?.to_string()); } match ( - vm.get_attribute_opt(obj.clone(), identifier!(vm, __qualname__))? + vm.get_attribute_opt(obj.to_owned(), identifier!(vm, __qualname__))? .and_then(|o| o.downcast_ref::().map(|n| n.to_string())), - vm.get_attribute_opt(obj.clone(), identifier!(vm, __module__))? + vm.get_attribute_opt(obj.to_owned(), identifier!(vm, __module__))? .and_then(|o| o.downcast_ref::().map(|m| m.to_string())), ) { (None, _) | (_, None) => Ok(obj.repr(vm)?.to_string()), @@ -160,17 +160,17 @@ impl PyGenericAlias { .get(i) .cloned() .ok_or_else(|| vm.new_index_error("list index out of range"))?; - parts.push(repr_item(item, vm)?); + parts.push(repr_item(&item, vm)?); } Ok(format!("[{}]", parts.join(", "))) } else { - repr_item(obj, vm) + repr_item(&obj, vm) } } let repr_str = format!( "{}[{}]", - repr_item(self.origin.clone(), vm)?, + repr_item(&self.origin, vm)?, if self.args.is_empty() { "()".to_owned() } else { @@ -219,14 +219,8 @@ impl PyGenericAlias { } } - fn __getitem__(zelf: PyRef, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let new_args = subs_parameters( - zelf.to_owned().into(), - zelf.args.clone(), - zelf.parameters.clone(), - needle, - vm, - )?; + fn __getitem__(zelf: &Py, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let new_args = subs_parameters(zelf.as_object(), &zelf.args, &zelf.parameters, needle, vm)?; Ok(Self::new(zelf.origin.clone(), new_args, false, vm)?.into_pyobject(vm)) } @@ -235,7 +229,8 @@ impl PyGenericAlias { fn __dir__(&self, vm: &VirtualMachine) -> PyResult { let dir = vm.dir(Some(self.__origin__()))?; for exc in &ATTR_EXCEPTIONS { - if !dir.__contains__((*exc).to_pyobject(vm), vm)? { + let exc_obj = (*exc).to_pyobject(vm); + if !dir.__contains__(&exc_obj, vm)? { dir.append((*exc).to_pyobject(vm)); } } @@ -449,9 +444,9 @@ fn unpack_args(item: PyObjectRef, vm: &VirtualMachine) -> PyTupleRef { // _Py_subs_parameters pub(crate) fn subs_parameters( - alias: PyObjectRef, // = self - args: PyTupleRef, - parameters: PyTupleRef, + alias: &PyObject, // = self + args: &Py, + parameters: &Py, item: PyObjectRef, vm: &VirtualMachine, ) -> PyResult { @@ -464,17 +459,17 @@ pub(crate) fn subs_parameters( let mut item: PyObjectRef = unpack_args(item, vm).into(); // Step 2: Call __typing_prepare_subst__ on each parameter - for param in parameters.iter() { + for param in parameters { if let Ok(prepare) = param.get_attr(identifier!(vm, __typing_prepare_subst__), vm) && !prepare.is(&vm.ctx.none) { // Call prepare(self, item) item = if item.try_to_ref::(vm).is_ok() { - prepare.call((alias.clone(), item.clone()), vm)? + prepare.call((alias.to_owned(), item.clone()), vm)? } else { // Create a tuple with the single item's "O(O)" format let tuple_args = PyTuple::new_ref(vec![item.clone()], &vm.ctx); - prepare.call((alias.clone(), tuple_args.to_pyobject(vm)), vm)? + prepare.call((alias.to_owned(), tuple_args.to_pyobject(vm)), vm)? }; } } @@ -500,7 +495,7 @@ pub(crate) fn subs_parameters( // Step 4: Replace all type variables let mut new_args = Vec::new(); - for arg in args.iter() { + for arg in args { // Skip PyType objects if arg.class().is(vm.ctx.types.type_type) { new_args.push(arg.clone()); @@ -516,13 +511,7 @@ pub(crate) fn subs_parameters( arg.downcast_ref::().unwrap().borrow_vec().to_vec() }; let sub_tuple = PyTuple::new_ref(sub_items, &vm.ctx); - let sub_result = subs_parameters( - alias.clone(), - sub_tuple, - parameters.clone(), - item.clone(), - vm, - )?; + let sub_result = subs_parameters(alias, &sub_tuple, parameters, item.clone(), vm)?; let substituted: PyObjectRef = if is_list { // Convert tuple back to list PyList::from(sub_result.as_slice().to_vec()) @@ -544,10 +533,10 @@ pub(crate) fn subs_parameters( if let Some(iparam) = tuple_index(parameters.as_slice(), arg) { subst.call((arg_items[iparam].clone(),), vm)? } else { - subs_tvars(arg.clone(), ¶meters, &arg_items, vm)? + subs_tvars(arg.clone(), parameters, &arg_items, vm)? } } else { - subs_tvars(arg.clone(), ¶meters, &arg_items, vm)? + subs_tvars(arg.clone(), parameters, &arg_items, vm)? }; if unpack { @@ -574,7 +563,7 @@ impl AsMapping for PyGenericAlias { static AS_MAPPING: LazyLock = LazyLock::new(|| PyMappingMethods { subscript: atomic_func!(|mapping, needle, vm| { let zelf = PyGenericAlias::mapping_downcast(mapping); - PyGenericAlias::__getitem__(zelf.to_owned(), needle.to_owned(), vm) + PyGenericAlias::__getitem__(zelf, needle.to_owned(), vm) }), ..PyMappingMethods::NOT_IMPLEMENTED }); diff --git a/crates/vm/src/builtins/int.rs b/crates/vm/src/builtins/int.rs index c9b687168..23f91c629 100644 --- a/crates/vm/src/builtins/int.rs +++ b/crates/vm/src/builtins/int.rs @@ -379,7 +379,7 @@ impl PyInt { } #[inline] - fn int_op(&self, other: PyObjectRef, op: F) -> PyArithmeticValue + fn int_op(&self, other: &PyObject, op: F) -> PyArithmeticValue where F: Fn(&BigInt, &BigInt) -> BigInt, { @@ -390,7 +390,7 @@ impl PyInt { } #[inline] - fn general_op(&self, other: PyObjectRef, op: F, vm: &VirtualMachine) -> PyResult + fn general_op(&self, other: &PyObject, op: F, vm: &VirtualMachine) -> PyResult where F: Fn(&BigInt, &BigInt) -> PyResult, { @@ -409,18 +409,18 @@ impl PyInt { )] impl PyInt { pub(crate) fn __xor__(&self, other: PyObjectRef) -> PyArithmeticValue { - self.int_op(other, |a, b| a ^ b) + self.int_op(&other, |a, b| a ^ b) } pub(crate) fn __or__(&self, other: PyObjectRef) -> PyArithmeticValue { - self.int_op(other, |a, b| a | b) + self.int_op(&other, |a, b| a | b) } pub(crate) fn __and__(&self, other: PyObjectRef) -> PyArithmeticValue { - self.int_op(other, |a, b| a & b) + self.int_op(&other, |a, b| a & b) } - fn modpow(&self, other: PyObjectRef, modulus: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn modpow(&self, other: &PyObject, modulus: &PyObject, vm: &VirtualMachine) -> PyResult { if other.downcast_ref::().is_none() { return Ok(vm.ctx.not_implemented()); } @@ -757,9 +757,9 @@ impl PyInt { power: Some(|a, b, c, vm| { if let Some(a) = a.downcast_ref::() { if vm.is_none(c) { - a.general_op(b.to_owned(), |a, b| inner_pow(a, b, vm), vm) + a.general_op(b, |a, b| inner_pow(a, b, vm), vm) } else { - a.modpow(b.to_owned(), c.to_owned(), vm) + a.modpow(b, c, vm) } } else { Ok(vm.ctx.not_implemented()) diff --git a/crates/vm/src/builtins/iter.rs b/crates/vm/src/builtins/iter.rs index b5d710bef..856650643 100644 --- a/crates/vm/src/builtins/iter.rs +++ b/crates/vm/src/builtins/iter.rs @@ -4,7 +4,7 @@ use super::{PyInt, PyTupleRef, PyType}; use crate::{ - Context, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, + Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, class::PyClassImpl, function::ArgCallable, object::{Traverse, TraverseFn}, @@ -51,7 +51,7 @@ impl PositionIterInternal { } } - pub fn set_state(&mut self, state: PyObjectRef, f: F, vm: &VirtualMachine) -> PyResult<()> + pub fn set_state(&mut self, state: &PyObject, f: F, vm: &VirtualMachine) -> PyResult<()> where F: FnOnce(&T, usize) -> usize, { @@ -283,7 +283,7 @@ impl PySequenceIterator { #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.internal.lock().set_state(state, |_, pos| pos, vm) + self.internal.lock().set_state(&state, |_, pos| pos, vm) } } diff --git a/crates/vm/src/builtins/list.rs b/crates/vm/src/builtins/list.rs index 49ed1f1b3..537f0ca67 100644 --- a/crates/vm/src/builtins/list.rs +++ b/crates/vm/src/builtins/list.rs @@ -217,8 +217,8 @@ impl PyList { Ok(Self::from(elements).into_ref(&vm.ctx)) } - fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { - self.concat(&other, vm) + fn __add__(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult> { + self.concat(other, vm) } fn inplace_concat( @@ -315,11 +315,11 @@ impl PyList { fn __setitem__( &self, - needle: PyObjectRef, + needle: &PyObject, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - self._setitem(&needle, value, vm) + self._setitem(needle, value, vm) } fn __mul__(&self, n: ArgSize, vm: &VirtualMachine) -> PyResult> { @@ -335,8 +335,8 @@ impl PyList { self.mut_count(vm, &value) } - pub(crate) fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self.mut_contains(vm, &needle) + pub(crate) fn __contains__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + self.mut_contains(vm, needle) } #[pymethod] @@ -395,8 +395,8 @@ impl PyList { } } - fn __delitem__(&self, subscript: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self._delitem(&subscript, vm) + fn __delitem__(&self, subscript: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + self._delitem(subscript, vm) } #[pymethod] @@ -906,7 +906,7 @@ impl PyListIterator { fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal .lock() - .set_state(state, |obj, pos| pos.min(obj.__len__()), vm) + .set_state(&state, |obj, pos| pos.min(obj.__len__()), vm) } #[pymethod] @@ -970,7 +970,7 @@ impl PyListReverseIterator { fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal .lock() - .set_state(state, |obj, pos| pos.min(obj.__len__()), vm) + .set_state(&state, |obj, pos| pos.min(obj.__len__()), vm) } #[pymethod] diff --git a/crates/vm/src/builtins/mappingproxy.rs b/crates/vm/src/builtins/mappingproxy.rs index f8c7677e5..4b6d27be1 100644 --- a/crates/vm/src/builtins/mappingproxy.rs +++ b/crates/vm/src/builtins/mappingproxy.rs @@ -93,10 +93,10 @@ impl PyMappingProxy { ))) } - fn get_inner(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult> { + fn get_inner(&self, key: &PyObject, vm: &VirtualMachine) -> PyResult> { match &self.mapping { - MappingProxyInner::Class(class) => Self::class_get(class, &key, vm), - MappingProxyInner::Mapping(mapping) => mapping.mapping().subscript(&*key, vm).map(Some), + MappingProxyInner::Class(class) => Self::class_get(class, key, vm), + MappingProxyInner::Mapping(mapping) => mapping.mapping().subscript(key, vm).map(Some), } } @@ -129,7 +129,7 @@ impl PyMappingProxy { } pub fn __getitem__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self.get_inner(key.clone(), vm)? + self.get_inner(&key, vm)? .ok_or_else(|| vm.new_key_error(key)) } @@ -151,8 +151,8 @@ impl PyMappingProxy { } } - pub fn __contains__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self._contains(&key, vm) + pub fn __contains__(&self, key: &PyObject, vm: &VirtualMachine) -> PyResult { + self._contains(key, vm) } fn to_object(&self, vm: &VirtualMachine) -> PyResult { @@ -227,8 +227,8 @@ impl PyMappingProxy { ))) } - fn __or__(&self, args: PyObjectRef, vm: &VirtualMachine) -> PyResult { - vm._or(self.copy(vm)?.as_ref(), args.as_ref()) + fn __or__(&self, args: &PyObject, vm: &VirtualMachine) -> PyResult { + vm._or(self.copy(vm)?.as_ref(), args) } } diff --git a/crates/vm/src/builtins/memory.rs b/crates/vm/src/builtins/memory.rs index 062db05f4..cb53dbdc9 100644 --- a/crates/vm/src/builtins/memory.rs +++ b/crates/vm/src/builtins/memory.rs @@ -1,6 +1,6 @@ use super::{ PositionIterInternal, PyBytes, PyBytesRef, PyGenericAlias, PyInt, PyListRef, PySlice, PyStr, - PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, PyUtf8StrRef, iter::builtins_iter, + PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, PyUtf8Str, PyUtf8StrRef, iter::builtins_iter, locked_next, }; use crate::common::lock::LazyLock; @@ -1017,7 +1017,7 @@ impl PyMemoryView { Err(vm.new_value_error("memoryview.index(x): x not in memoryview")) } - fn cast_to_1d(&self, format: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult { + fn cast_to_1d(&self, format: &Py, vm: &VirtualMachine) -> PyResult { let format_str = format.as_str(); let Some(dest_char) = Self::native_fmtchar(format_str) else { return Err(vm.new_value_error( @@ -1097,7 +1097,7 @@ impl PyMemoryView { return Err(vm.new_type_error("memoryview: cast must be 1D -> ND or ND -> 1D")); } - let mut other = self.cast_to_1d(format, vm)?; + let mut other = self.cast_to_1d(&format, vm)?; let itemsize = other.desc.itemsize; // 0 ndim is single item, so the buffer has to be that one item @@ -1151,7 +1151,7 @@ impl PyMemoryView { Ok(other.into_ref(&vm.ctx)) } else { - Ok(self.cast_to_1d(format, vm)?.into_ref(&vm.ctx)) + Ok(self.cast_to_1d(&format, vm)?.into_ref(&vm.ctx)) } } } @@ -1562,7 +1562,7 @@ pub(crate) fn buffer_from_python_getbuffer( // wrap_releasebuffer pub(crate) fn release_buffer_from_python( obj: &PyObject, - mv: PyRef, + mv: &Py, vm: &VirtualMachine, ) -> PyResult<()> { let view_obj = &mv.buffer.obj; diff --git a/crates/vm/src/builtins/object.rs b/crates/vm/src/builtins/object.rs index d8507b1e5..9955b0cbd 100644 --- a/crates/vm/src/builtins/object.rs +++ b/crates/vm/src/builtins/object.rs @@ -702,14 +702,14 @@ fn get_items_iter(obj: &PyObject, vm: &VirtualMachine) -> PyResult<(PyObjectRef, } /// reduce_newobj - creates reduce tuple for protocol >= 2 -fn reduce_newobj(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { +fn reduce_newobj(obj: &PyObject, vm: &VirtualMachine) -> PyResult { // Check if type has tp_new let cls = obj.class(); if cls.slots.new.load().is_none() { return Err(vm.new_type_error(format!("cannot pickle '{}' object", cls.name()))); } - let (args, kwargs) = get_new_arguments(&obj, vm)?; + let (args, kwargs) = get_new_arguments(obj, vm)?; let copyreg = vm.import("copyreg", 0)?; @@ -752,9 +752,9 @@ fn reduce_newobj(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { let is_dict = obj.fast_isinstance(vm.ctx.types.dict_type); let required = !(has_args || is_list || is_dict); - let state = object_getstate(&obj, required, vm)?; + let state = object_getstate(obj, required, vm)?; - let (listitems, dictitems) = get_items_iter(&obj, vm)?; + let (listitems, dictitems) = get_items_iter(obj, vm)?; let result = vm .ctx @@ -764,7 +764,7 @@ fn reduce_newobj(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { fn common_reduce(obj: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult { if proto >= 2 { - reduce_newobj(obj, vm) + reduce_newobj(&obj, vm) } else { let copyreg = vm.import("copyreg", 0)?; let reduce_ex = copyreg.get_attr("_reduce_ex", vm)?; diff --git a/crates/vm/src/builtins/property.rs b/crates/vm/src/builtins/property.rs index d4bd6cdd5..246fb8635 100644 --- a/crates/vm/src/builtins/property.rs +++ b/crates/vm/src/builtins/property.rs @@ -204,7 +204,7 @@ impl PyProperty { // Helper method to create a new property with updated attributes fn clone_property_with( - zelf: PyRef, + zelf: &Py, new_getter: Option, new_setter: Option, new_deleter: Option, @@ -252,7 +252,7 @@ impl PyProperty { getter: Option, vm: &VirtualMachine, ) -> PyResult> { - Self::clone_property_with(zelf, getter, None, None, vm) + Self::clone_property_with(&zelf, getter, None, None, vm) } #[pymethod] @@ -261,7 +261,7 @@ impl PyProperty { setter: Option, vm: &VirtualMachine, ) -> PyResult> { - Self::clone_property_with(zelf, None, setter, None, vm) + Self::clone_property_with(&zelf, None, setter, None, vm) } #[pymethod] @@ -270,7 +270,7 @@ impl PyProperty { deleter: Option, vm: &VirtualMachine, ) -> PyResult> { - Self::clone_property_with(zelf, None, None, deleter, vm) + Self::clone_property_with(&zelf, None, None, deleter, vm) } #[pygetset] diff --git a/crates/vm/src/builtins/range.rs b/crates/vm/src/builtins/range.rs index 1252bcb5c..ee7c452dd 100644 --- a/crates/vm/src/builtins/range.rs +++ b/crates/vm/src/builtins/range.rs @@ -242,8 +242,8 @@ impl PyRange { fn new_from( cls: PyTypeRef, - start: PyObjectRef, - stop: PyObjectRef, + start: &PyObject, + stop: &PyObject, step: OptionalArg, vm: &VirtualMachine, ) -> PyResult> { @@ -357,8 +357,9 @@ impl PyRange { let stop = args.bind_for(vm, Self::NAME)?; Self::new(cls, stop, vm) } else { - let (start, stop, step) = args.bind_for(vm, Self::NAME)?; - Self::new_from(cls, start, stop, step, vm) + let (start, stop, step): (PyObjectRef, PyObjectRef, OptionalArg) = + args.bind_for(vm, Self::NAME)?; + Self::new_from(cls, &start, &stop, step, vm) }?; Ok(range.into()) @@ -389,8 +390,8 @@ impl Py { } } - fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> bool { - self.contains_inner(&needle, vm) + fn __contains__(&self, needle: &PyObject, vm: &VirtualMachine) -> bool { + self.contains_inner(needle, vm) } #[pymethod] @@ -612,7 +613,7 @@ impl PyLongRangeIterator { #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.index.store(range_state(&self.length, state, vm)?); + self.index.store(range_state(&self.length, &state, vm)?); Ok(()) } @@ -674,7 +675,7 @@ impl PyRangeIterator { #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.index - .store(range_state(&BigInt::from(self.length), state, vm)?); + .store(range_state(&BigInt::from(self.length), &state, vm)?); Ok(()) } @@ -736,7 +737,7 @@ fn range_iter_reduce( } // Silently clips state (i.e index) in range [0, usize::MAX]. -fn range_state(length: &BigInt, state: PyObjectRef, vm: &VirtualMachine) -> PyResult { +fn range_state(length: &BigInt, state: &PyObject, vm: &VirtualMachine) -> PyResult { if let Some(i) = state.downcast_ref::() { let mut index = i.as_bigint(); let max_usize = BigInt::from(usize::MAX); diff --git a/crates/vm/src/builtins/set.rs b/crates/vm/src/builtins/set.rs index 1fc7c25b3..d9a82f337 100644 --- a/crates/vm/src/builtins/set.rs +++ b/crates/vm/src/builtins/set.rs @@ -102,7 +102,7 @@ impl PyFrozenSet { ) -> PyResult { let inner = PySetInner::default(); for elem in it { - inner.add(elem, vm)?; + inner.add(&elem, vm)?; } // FIXME: empty set check Ok(Self { @@ -190,7 +190,8 @@ impl PySetInner { { let set = Self::default(); for item in iter { - set.add(item?, vm)?; + let item = item?; + set.add(&item, vm)?; } Ok(set) } @@ -284,12 +285,13 @@ impl PySetInner { let set = self.clone(); if let Some(elements) = Self::cached_hashes(other.as_object(), vm) { for (item, hash) in elements { - set.add_known_hash(item, hash, vm)?; + set.add_known_hash(&item, hash, vm)?; } return Ok(set); } for item in other.iter(vm)? { - set.add(item?, vm)?; + let item = item?; + set.add(&item, vm)?; } Ok(set) @@ -300,7 +302,7 @@ impl PySetInner { if let Some(elements) = Self::cached_hashes(other.as_object(), vm) { for (obj, hash) in elements { if self.contains_known_hash(&obj, hash, vm)? { - set.add_known_hash(obj, hash, vm)?; + set.add_known_hash(&obj, hash, vm)?; } } return Ok(set); @@ -308,7 +310,7 @@ impl PySetInner { for item in other.iter(vm)? { let obj = item?; if self.contains(&obj, vm)? { - set.add(obj, vm)?; + set.add(&obj, vm)?; } } Ok(set) @@ -390,21 +392,21 @@ impl PySetInner { ) } - fn add(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - let result = self.content.insert(vm, &*item, ()); - Self::wrap_unhashable_error(result, &item, vm) + fn add(&self, item: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + let result = self.content.insert(vm, item, ()); + Self::wrap_unhashable_error(result, item, vm) } /// [`Self::add`] with a known hash. - fn add_known_hash(&self, item: PyObjectRef, hash: PyHash, vm: &VirtualMachine) -> PyResult<()> { - let result = self.content.insert_known_hash(vm, &*item, hash, ()); - Self::wrap_unhashable_error(result, &item, vm) + fn add_known_hash(&self, item: &PyObject, hash: PyHash, vm: &VirtualMachine) -> PyResult<()> { + let result = self.content.insert_known_hash(vm, item, hash, ()); + Self::wrap_unhashable_error(result, item, vm) } - fn remove(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + fn remove(&self, item: &PyObject, vm: &VirtualMachine) -> PyResult<()> { let result = - self.retry_op_with_frozenset(&item, vm, |item, vm| self.content.delete(vm, item)); - Self::wrap_unhashable_error(result, &item, vm) + self.retry_op_with_frozenset(item, vm, |item, vm| self.content.delete(vm, item)); + Self::wrap_unhashable_error(result, item, vm) } fn discard(&self, item: &PyObject, vm: &VirtualMachine) -> PyResult { @@ -438,7 +440,8 @@ impl PySetInner { ) -> PyResult<()> { for iterable in others { for item in iterable.iter(vm)? { - self.add(item?, vm)?; + let item = item?; + self.add(&item, vm)?; } } Ok(()) @@ -450,11 +453,12 @@ impl PySetInner { self.merge_set(any_set, vm) // check Dict } else if let Ok(dict) = iterable.to_owned().downcast_exact::(vm) { - self.merge_dict(dict.into_pyref(), vm) + self.merge_dict(&dict, vm) } else { // add iterable that is not AnySet or Dict for item in iterable.try_into_value::(vm)?.iter(vm)? { - self.add(item?, vm)?; + let item = item?; + self.add(&item, vm)?; } Ok(()) } @@ -462,14 +466,14 @@ impl PySetInner { fn merge_set(&self, any_set: AnySet, vm: &VirtualMachine) -> PyResult<()> { for (item, hash) in any_set.as_inner().content.keys_with_hashes() { - self.add_known_hash(item, hash, vm)?; + self.add_known_hash(&item, hash, vm)?; } Ok(()) } - fn merge_dict(&self, dict: PyDictRef, vm: &VirtualMachine) -> PyResult<()> { + fn merge_dict(&self, dict: &Py, vm: &VirtualMachine) -> PyResult<()> { for (key, hash) in dict._as_dict_inner().keys_with_hashes() { - self.add_known_hash(key, hash, vm)?; + self.add_known_hash(&key, hash, vm)?; } Ok(()) } @@ -482,7 +486,7 @@ impl PySetInner { let temp_inner = self.fold_op(others, Self::intersection, vm)?; self.clear(); for (obj, hash) in temp_inner.content.keys_with_hashes() { - self.add_known_hash(obj, hash, vm)?; + self.add_known_hash(&obj, hash, vm)?; } Ok(()) } @@ -784,12 +788,12 @@ impl PySet { #[pymethod] pub fn add(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.inner.add(object, vm) + self.inner.add(&object, vm) } #[pymethod] fn remove(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.inner.remove(object, vm) + self.inner.remove(&object, vm) } #[pymethod] diff --git a/crates/vm/src/builtins/staticmethod.rs b/crates/vm/src/builtins/staticmethod.rs index b069675a3..cd1d945da 100644 --- a/crates/vm/src/builtins/staticmethod.rs +++ b/crates/vm/src/builtins/staticmethod.rs @@ -108,9 +108,9 @@ impl PyStaticMethod { #[pygetset] fn __annotations__(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let callable = zelf.callable.lock().clone(); + let callable = zelf.callable.lock(); descriptor_get_wrapped_attribute( - callable, + &callable, zelf.as_object(), identifier!(vm.ctx, __annotations__), vm, @@ -134,9 +134,9 @@ impl PyStaticMethod { #[pygetset] fn __annotate__(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let callable = zelf.callable.lock().clone(); + let callable = zelf.callable.lock(); descriptor_get_wrapped_attribute( - callable, + &callable, zelf.as_object(), identifier!(vm.ctx, __annotate__), vm, diff --git a/crates/vm/src/builtins/str.rs b/crates/vm/src/builtins/str.rs index 96328c9d1..10d891b6a 100644 --- a/crates/vm/src/builtins/str.rs +++ b/crates/vm/src/builtins/str.rs @@ -339,7 +339,7 @@ impl PyStrIterator { internal.1 = usize::MAX; internal .0 - .set_state(state, |obj, pos| pos.min(obj.char_len()), vm) + .set_state(&state, |obj, pos| pos.min(obj.char_len()), vm) } #[pymethod] @@ -658,7 +658,7 @@ impl Py { ) )] impl PyStr { - fn __add__(zelf: PyRef, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn __add__(zelf: PyRef, other: &PyObject, vm: &VirtualMachine) -> PyResult { if let Some(other) = other.downcast_ref::() { let bytes = zelf.as_wtf8().py_add(other.as_wtf8()); Ok(unsafe { @@ -669,7 +669,7 @@ impl PyStr { .to_pyobject(vm)) } else { // hack to get around not distinguishing number add from seq concat - if let Some(radd) = vm.get_method(other.clone(), identifier!(vm, __radd__)) { + if let Some(radd) = vm.get_method(other.to_owned(), identifier!(vm, __radd__)) { let result = radd?.call((zelf,), vm)?; // CPython reaches `str`'s sq_concat once the reflected call declines, so a // `__radd__` returning NotImplemented must still report the concat error @@ -696,8 +696,8 @@ impl PyStr { } } - fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self._contains(&needle, vm) + fn __contains__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + self._contains(needle, vm) } fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { @@ -708,8 +708,8 @@ impl PyStr { Ok(item) } - fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self._getitem(&needle, vm) + fn __getitem__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + self._getitem(needle, vm) } #[inline] @@ -1713,7 +1713,7 @@ impl AsSequence for PyStr { length: atomic_func!(|seq, _vm| Ok(PyStr::sequence_downcast(seq).len())), concat: atomic_func!(|seq, other, vm| { let zelf = PyStr::sequence_downcast(seq); - PyStr::__add__(zelf.to_owned(), other.to_owned(), vm) + PyStr::__add__(zelf.to_owned(), other, vm) }), repeat: atomic_func!(|seq, n, vm| { let zelf = PyStr::sequence_downcast(seq); diff --git a/crates/vm/src/builtins/super.rs b/crates/vm/src/builtins/super.rs index dbff3156e..0da7b60d2 100644 --- a/crates/vm/src/builtins/super.rs +++ b/crates/vm/src/builtins/super.rs @@ -6,7 +6,7 @@ See also [CPython source code.](https://github.com/python/cpython/blob/50b48572d use super::{PyStr, PyType, PyTypeRef}; use crate::{ - AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, + AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::function::PyCell, class::PyClassImpl, common::lock::PyRwLock, @@ -31,7 +31,7 @@ impl PySuperInner { let obj = if vm.is_none(&obj) { None } else { - let obj_type = super_check(typ.clone(), obj.clone(), vm)?; + let obj_type = super_check(&typ, &obj, vm)?; Some((obj, obj_type)) }; Ok(Self { typ, obj }) @@ -254,21 +254,21 @@ impl Representable for PySuper { } } -fn super_check(ty: PyTypeRef, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let typ = match obj.clone().downcast::() { - Ok(cls) if cls.fast_issubclass(&ty) => return Ok(cls), +fn super_check(ty: &Py, obj: &PyObject, vm: &VirtualMachine) -> PyResult { + let typ = match obj.to_owned().downcast::() { + Ok(cls) if cls.fast_issubclass(ty) => return Ok(cls), Ok(cls) => Some(cls), Err(_) => None, }; - if obj.fast_isinstance(&ty) { + if obj.fast_isinstance(ty) { return Ok(obj.class().to_owned()); } let class_attr = obj.get_attr("__class__", vm)?; if let Ok(cls) = class_attr.downcast::() && !cls.is(obj.class()) - && cls.fast_issubclass(&ty) + && cls.fast_issubclass(ty) { return Ok(cls); } diff --git a/crates/vm/src/builtins/template.rs b/crates/vm/src/builtins/template.rs index 5eb33a6a4..6fcded566 100644 --- a/crates/vm/src/builtins/template.rs +++ b/crates/vm/src/builtins/template.rs @@ -182,8 +182,8 @@ impl PyTemplate { Ok(template.into_ref(&vm.ctx)) } - fn __add__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { - self.concat(&other, vm) + fn __add__(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult> { + self.concat(other, vm) } #[pyclassmethod] diff --git a/crates/vm/src/builtins/tuple.rs b/crates/vm/src/builtins/tuple.rs index 5ee66a3c3..35121d083 100644 --- a/crates/vm/src/builtins/tuple.rs +++ b/crates/vm/src/builtins/tuple.rs @@ -473,8 +473,8 @@ impl PyTuple { } } - fn __getitem__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self._getitem(&needle, vm) + fn __getitem__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + self._getitem(needle, vm) } #[pymethod] @@ -502,8 +502,8 @@ impl PyTuple { Ok(false) } - fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self._contains(&needle, vm) + fn __contains__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + self._contains(needle, vm) } #[pymethod] @@ -704,7 +704,7 @@ impl PyTupleIterator { fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal .lock() - .set_state(state, |obj, pos| pos.min(obj.len()), vm) + .set_state(&state, |obj, pos| pos.min(obj.len()), vm) } #[pymethod] diff --git a/crates/vm/src/builtins/type.rs b/crates/vm/src/builtins/type.rs index 1bfef52d3..bb2b4aef5 100644 --- a/crates/vm/src/builtins/type.rs +++ b/crates/vm/src/builtins/type.rs @@ -1545,7 +1545,7 @@ impl PyType { subtype = subtype.name(), ))); } - call_slot_new(zelf, subtype, args, vm) + call_slot_new(&zelf, subtype, args, vm) } fn name_inner<'a, R: 'a>( @@ -3344,7 +3344,7 @@ pub(crate) fn init(ctx: &'static Context) { } pub(crate) fn call_slot_new( - typ: PyTypeRef, + typ: &Py, subtype: PyTypeRef, args: FuncArgs, vm: &VirtualMachine, diff --git a/crates/vm/src/builtins/union.rs b/crates/vm/src/builtins/union.rs index c1be5c8ec..3a779ae89 100644 --- a/crates/vm/src/builtins/union.rs +++ b/crates/vm/src/builtins/union.rs @@ -59,25 +59,25 @@ impl PyUnion { } fn repr(&self, vm: &VirtualMachine) -> PyResult { - fn repr_item(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn repr_item(obj: &PyObject, vm: &VirtualMachine) -> PyResult { if obj.is(vm.ctx.types.none_type) { return Ok("None".to_string()); } if vm - .get_attribute_opt(obj.clone(), identifier!(vm, __origin__))? + .get_attribute_opt(obj.to_owned(), identifier!(vm, __origin__))? .is_some() && vm - .get_attribute_opt(obj.clone(), identifier!(vm, __args__))? + .get_attribute_opt(obj.to_owned(), identifier!(vm, __args__))? .is_some() { return Ok(obj.repr(vm)?.to_string()); } match ( - vm.get_attribute_opt(obj.clone(), identifier!(vm, __qualname__))? + vm.get_attribute_opt(obj.to_owned(), identifier!(vm, __qualname__))? .and_then(|o| o.downcast_ref::().map(|n| n.to_string())), - vm.get_attribute_opt(obj.clone(), identifier!(vm, __module__))? + vm.get_attribute_opt(obj.to_owned(), identifier!(vm, __module__))? .and_then(|o| o.downcast_ref::().map(|m| m.to_string())), ) { (None, _) | (_, None) => Ok(obj.repr(vm)?.to_string()), @@ -92,7 +92,7 @@ impl PyUnion { Ok(self .args .iter() - .map(|o| repr_item(o.clone(), vm)) + .map(|o| repr_item(o, vm)) .collect::>>()? .join(" | ")) } @@ -194,7 +194,7 @@ impl PyUnion { } } -fn is_unionable(obj: PyObjectRef, vm: &VirtualMachine) -> bool { +fn is_unionable(obj: &PyObject, vm: &VirtualMachine) -> bool { let cls = obj.class(); cls.is(vm.ctx.types.none_type) || obj.downcastable::() @@ -205,7 +205,7 @@ fn is_unionable(obj: PyObjectRef, vm: &VirtualMachine) -> bool { fn type_check(arg: PyObjectRef, vm: &VirtualMachine) -> PyResult { // Fast path to avoid calling into typing.py - if is_unionable(arg.clone(), vm) { + if is_unionable(&arg, vm) { return Ok(arg); } let message_str: PyObjectRef = vm @@ -215,14 +215,14 @@ fn type_check(arg: PyObjectRef, vm: &VirtualMachine) -> PyResult { call_typing_func_object(vm, "_type_check", (arg, message_str)) } -fn has_union_operands(a: PyObjectRef, b: PyObjectRef, vm: &VirtualMachine) -> bool { +fn has_union_operands(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> bool { let union_type = vm.ctx.types.union_type; a.class().is(union_type) || b.class().is(union_type) } pub(crate) fn or_op(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { - if !has_union_operands(zelf.clone(), other.clone(), vm) - && (!is_unionable(zelf.clone(), vm) || !is_unionable(other.clone(), vm)) + if !has_union_operands(&zelf, &other, vm) + && (!is_unionable(&zelf, vm) || !is_unionable(&other, vm)) { return Ok(vm.ctx.not_implemented()); } @@ -371,11 +371,11 @@ pub fn make_union(args: &Py, vm: &VirtualMachine) -> PyResult { } impl PyUnion { - fn getitem(zelf: PyRef, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn getitem(zelf: &Py, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { let new_args = genericalias::subs_parameters( - zelf.to_owned().into(), - zelf.args.clone(), - zelf.parameters.clone(), + zelf.as_object(), + &zelf.args, + &zelf.parameters, needle, vm, )?; @@ -397,7 +397,7 @@ impl AsMapping for PyUnion { static AS_MAPPING: LazyLock = LazyLock::new(|| PyMappingMethods { subscript: atomic_func!(|mapping, needle, vm| { let zelf = PyUnion::mapping_downcast(mapping); - PyUnion::getitem(zelf.to_owned(), needle.to_owned(), vm) + PyUnion::getitem(zelf, needle.to_owned(), vm) }), ..PyMappingMethods::NOT_IMPLEMENTED }); diff --git a/crates/vm/src/builtins/weakproxy.rs b/crates/vm/src/builtins/weakproxy.rs index 82736c3cf..0a959e4c9 100644 --- a/crates/vm/src/builtins/weakproxy.rs +++ b/crates/vm/src/builtins/weakproxy.rs @@ -138,30 +138,25 @@ impl PyWeakProxy { let obj = self.try_upgrade(vm)?; reversed(obj, vm) } - fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn __contains__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { self.try_upgrade(vm)? .sequence_unchecked() - .contains(&needle, vm) + .contains(needle, vm) } - fn getitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { let obj = self.try_upgrade(vm)?; - obj.get_item(&*needle, vm) + obj.get_item(needle, vm) } - fn setitem( - &self, - needle: PyObjectRef, - value: PyObjectRef, - vm: &VirtualMachine, - ) -> PyResult<()> { + fn setitem(&self, needle: &PyObject, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let obj = self.try_upgrade(vm)?; - obj.set_item(&*needle, value, vm) + obj.set_item(needle, value, vm) } - fn delitem(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + fn delitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<()> { let obj = self.try_upgrade(vm)?; - obj.del_item(&*needle, vm) + obj.del_item(needle, vm) } } @@ -355,7 +350,7 @@ impl AsSequence for PyWeakProxy { static AS_SEQUENCE: LazyLock = LazyLock::new(|| PySequenceMethods { length: atomic_func!(|seq, vm| PyWeakProxy::sequence_downcast(seq).len(vm)), contains: atomic_func!(|seq, needle, vm| { - PyWeakProxy::sequence_downcast(seq).__contains__(needle.to_owned(), vm) + PyWeakProxy::sequence_downcast(seq).__contains__(needle, vm) }), ..PySequenceMethods::NOT_IMPLEMENTED }); @@ -368,14 +363,14 @@ impl AsMapping for PyWeakProxy { static AS_MAPPING: PyMappingMethods = PyMappingMethods { length: atomic_func!(|mapping, vm| PyWeakProxy::mapping_downcast(mapping).len(vm)), subscript: atomic_func!(|mapping, needle, vm| { - PyWeakProxy::mapping_downcast(mapping).getitem(needle.to_owned(), vm) + PyWeakProxy::mapping_downcast(mapping).getitem(needle, vm) }), ass_subscript: atomic_func!(|mapping, needle, value, vm| { let zelf = PyWeakProxy::mapping_downcast(mapping); if let Some(value) = value { - zelf.setitem(needle.to_owned(), value, vm) + zelf.setitem(needle, value, vm) } else { - zelf.delitem(needle.to_owned(), vm) + zelf.delitem(needle, vm) } }), }; diff --git a/crates/vm/src/bytes_inner.rs b/crates/vm/src/bytes_inner.rs index 9a1ad616a..9640bc106 100644 --- a/crates/vm/src/bytes_inner.rs +++ b/crates/vm/src/bytes_inner.rs @@ -1,6 +1,6 @@ // spell-checker:ignore unchunked use crate::{ - AsObject, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject, + AsObject, Py, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, anystr::{self, AnyStr, AnyStrContainer, AnyStrWrapper}, builtins::{ @@ -69,14 +69,14 @@ impl ByteInnerNewOptions { } fn get_value_from_source( - source: PyObjectRef, + source: &PyObject, from_object: FromObject, vm: &VirtualMachine, ) -> PyResult { - from_object(vm, &source).map(|x| x.into()) + from_object(vm, source).map(|x| x.into()) } - fn get_value_from_size(size: PyIntRef, vm: &VirtualMachine) -> PyResult { + fn get_value_from_size(size: &Py, vm: &VirtualMachine) -> PyResult { let size = size .as_bigint() .to_isize() @@ -96,11 +96,11 @@ impl ByteInnerNewOptions { ) -> PyResult { match_class!(match obj { i @ PyInt => { - Self::get_value_from_size(i, vm) + Self::get_value_from_size(&i, vm) } _s @ PyStr => Err(vm.new_type_error(STRING_WITHOUT_ENCODING.to_owned())), obj => { - Self::get_value_from_source(obj, from_object, vm) + Self::get_value_from_source(&obj, from_object, vm) } }) } @@ -114,7 +114,7 @@ impl ByteInnerNewOptions { // Try __index__ first to handle int-like objects that might raise custom exceptions if let Some(index_result) = obj.try_index_opt(vm) { match index_result { - Ok(index) => Self::get_value_from_size(index, vm), + Ok(index) => Self::get_value_from_size(&index, vm), Err(e) => { // Only propagate non-TypeError exceptions // TypeError means the object doesn't support __index__, so fall back @@ -565,11 +565,11 @@ impl PyBytesInner { } /// Parse hex string from str or bytes-like object - pub fn fromhex_object(string: PyObjectRef, vm: &VirtualMachine) -> PyResult> { + pub fn fromhex_object(string: &PyObject, vm: &VirtualMachine) -> PyResult> { if let Some(s) = string.downcast_ref::() { Self::fromhex(s.as_bytes(), vm) } else if string.check_buffer() { - let buffer = PyBuffer::from_object(vm, &string, BufferFlags::SIMPLE)?; + let buffer = PyBuffer::from_object(vm, string, BufferFlags::SIMPLE)?; let borrowed = buffer .as_contiguous() .ok_or_else(|| vm.new_buffer_error("fromhex() requires a contiguous buffer"))?; diff --git a/crates/vm/src/codecs.rs b/crates/vm/src/codecs.rs index c07e33525..6e919ff56 100644 --- a/crates/vm/src/codecs.rs +++ b/crates/vm/src/codecs.rs @@ -1357,7 +1357,7 @@ fn is_translate_err(err: &PyObject, vm: &VirtualMachine) -> bool { err.fast_isinstance(vm.ctx.exceptions.unicode_translate_error) } -fn bad_err_type(err: PyObjectRef, vm: &VirtualMachine) -> PyBaseExceptionRef { +fn bad_err_type(err: &PyObject, vm: &VirtualMachine) -> PyBaseExceptionRef { vm.new_type_error(format!( "don't know how to handle {} in error callback", err.class().name() @@ -1375,7 +1375,7 @@ fn ignore_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(PyObjectRef let range = extract_unicode_error_range(&err, vm)?; Ok((vm.ctx.new_str(ascii!("")).into(), range.end)) } else { - Err(bad_err_type(err, vm)) + Err(bad_err_type(&err, vm)) } } @@ -1391,7 +1391,7 @@ fn replace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(PyObjectRe let replace = replacement_char.repeat(range.end - range.start); Ok((replace.to_pyobject(vm), range.end)) } else { - Err(bad_err_type(err, vm)) + Err(bad_err_type(&err, vm)) } } @@ -1402,7 +1402,7 @@ fn xmlcharrefreplace_errors( if is_encode_err(&err, vm) { call_native_encode_error(errors::XmlCharRefReplace, err, vm) } else { - Err(bad_err_type(err, vm)) + Err(bad_err_type(&err, vm)) } } @@ -1417,7 +1417,7 @@ fn backslashreplace_errors( } else if is_translate_err(&err, vm) { call_native_translate_error(errors::BackslashReplace, err, vm) } else { - Err(bad_err_type(err, vm)) + Err(bad_err_type(&err, vm)) } } @@ -1425,7 +1425,7 @@ fn namereplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(PyObje if is_encode_err(&err, vm) { call_native_encode_error(errors::NameReplace, err, vm) } else { - Err(bad_err_type(err, vm)) + Err(bad_err_type(&err, vm)) } } @@ -1435,7 +1435,7 @@ fn surrogatepass_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(PyOb } else if is_decode_err(&err, vm) { call_native_decode_error(SurrogatePass, err, vm) } else { - Err(bad_err_type(err, vm)) + Err(bad_err_type(&err, vm)) } } @@ -1445,6 +1445,6 @@ fn surrogateescape_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(Py } else if is_decode_err(&err, vm) { call_native_decode_error(errors::SurrogateEscape, err, vm) } else { - Err(bad_err_type(err, vm)) + Err(bad_err_type(&err, vm)) } } diff --git a/crates/vm/src/exceptions.rs b/crates/vm/src/exceptions.rs index a3113961a..2db1bc7ec 100644 --- a/crates/vm/src/exceptions.rs +++ b/crates/vm/src/exceptions.rs @@ -192,7 +192,7 @@ impl VirtualMachine { } let varargs = exc.args(); - let args_repr = vm.exception_args_as_string(varargs, true); + let args_repr = vm.exception_args_as_string(&varargs, true); let exc_class = exc.class(); @@ -352,7 +352,7 @@ impl VirtualMachine { } } - fn exception_args_as_string(&self, varargs: PyTupleRef, str_single: bool) -> Vec { + fn exception_args_as_string(&self, varargs: &Py, str_single: bool) -> Vec { let vm = self; match varargs.len() { 0 => vec![], @@ -779,7 +779,7 @@ impl PyBaseException { impl Py { #[pymethod] pub(super) fn __str__(&self, vm: &VirtualMachine) -> PyStrRef { - let str_args = vm.exception_args_as_string(self.args(), true); + let str_args = vm.exception_args_as_string(&self.args(), true); match str_args.into_iter().exactly_one() { Err(i) if i.len() == 0 => vm.ctx.empty_str.to_owned(), Ok(s) => s, @@ -874,7 +874,7 @@ impl Initializer for PyBaseException { impl Representable for PyBaseException { #[inline] fn repr_str(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let repr_args = vm.exception_args_as_string(zelf.args(), false); + let repr_args = vm.exception_args_as_string(&zelf.args(), false); let cls = zelf.class(); Ok(format!("{}({})", cls.name(), repr_args.iter().format(", "))) } @@ -1190,7 +1190,7 @@ fn make_arg_getter(idx: usize) -> impl Fn(PyBaseExceptionRef) -> Option, value: PySetterValue, vm: &VirtualMachine) { let mut args = exc.args.write(); let mut new_args = args.as_slice().to_vec(); // Ensure the message slot at index 0 always exists for SyntaxError.args. @@ -2130,7 +2130,7 @@ pub(super) mod types { fn __str__(zelf: &Py, vm: &VirtualMachine) -> PyStrRef { let args = zelf.args(); if args.len() == 1 { - vm.exception_args_as_string(args, false) + vm.exception_args_as_string(&args, false) .into_iter() .exactly_one() .unwrap() @@ -3452,12 +3452,12 @@ pub fn exception_group_match( /// Prepare exception for reraise in except* block. /// Implements _PyExc_PrepReraiseStar -pub fn prep_reraise_star(orig: PyObjectRef, excs: PyObjectRef, vm: &VirtualMachine) -> PyResult { +pub fn prep_reraise_star(orig: &PyObject, excs: &PyObject, vm: &VirtualMachine) -> PyResult { use crate::builtins::PyList; let excs_list = excs - .downcast::() - .map_err(|_| vm.new_type_error("expected list for prep_reraise_star"))?; + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("expected list for prep_reraise_star"))?; let excs_vec: Vec = excs_list.borrow_vec().to_vec(); @@ -3483,7 +3483,7 @@ pub fn prep_reraise_star(orig: PyObjectRef, excs: PyObjectRef, vm: &VirtualMachi continue; } // Check if this exception came from the original group - if is_exception_from_orig(&exc, &orig, vm) { + if is_exception_from_orig(&exc, orig, vm) { reraised.push(exc); } else { raised.push(exc); @@ -3496,7 +3496,7 @@ pub fn prep_reraise_star(orig: PyObjectRef, excs: PyObjectRef, vm: &VirtualMachi } // Project reraised exceptions onto original structure to preserve nesting - let reraised_eg = exception_group_projection(&orig, &reraised, vm)?; + let reraised_eg = exception_group_projection(orig, &reraised, vm)?; // If no new raised exceptions, just return the reraised projection if raised.is_empty() { diff --git a/crates/vm/src/frame.rs b/crates/vm/src/frame.rs index 96f00bfe0..4428984a7 100644 --- a/crates/vm/src/frame.rs +++ b/crates/vm/src/frame.rs @@ -2354,16 +2354,16 @@ impl FrameObject { /// `key in proxy`. pub(crate) fn framelocalsproxy_contains( &self, - key: PyObjectRef, + key: &PyObject, vm: &VirtualMachine, ) -> PyResult { self.check_locals_access(vm)?; - if self.framelocalsproxy_getkeyindex(&key, true, vm)?.is_some() { + if self.framelocalsproxy_getkeyindex(key, true, vm)?.is_some() { return Ok(true); } let extra = self.iframe().cold().f_extra_locals.lock().clone(); if let Some(extra) = extra { - return Ok(extra.get_item_opt(&*key, vm)?.is_some()); + return Ok(extra.get_item_opt(key, vm)?.is_some()); } Ok(false) } @@ -2372,17 +2372,17 @@ impl FrameObject { /// to the extra-locals side dict. pub(crate) fn framelocalsproxy_setitem( &self, - key: PyObjectRef, + key: &PyObject, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { self.check_locals_access(vm)?; - if let Some(i) = self.framelocalsproxy_getkeyindex(&key, false, vm)? { + if let Some(i) = self.framelocalsproxy_getkeyindex(key, false, vm)? { self.framelocalsproxy_setval(i, value); return Ok(()); } let extra = self.extra_locals_get_or_create(vm); - extra.set_item(&*key, value, vm) + extra.set_item(key, value, vm) } /// `del proxy[key]`: deleting a fast local raises ValueError; extra keys are @@ -2441,7 +2441,7 @@ impl FrameObject { match self.framelocalsproxy_getitem(key.clone(), vm) { Ok(value) => Ok(value), Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => { - self.framelocalsproxy_setitem(key, default.clone(), vm)?; + self.framelocalsproxy_setitem(&key, default.clone(), vm)?; Ok(default) } Err(e) => Err(e), @@ -12382,7 +12382,7 @@ impl ExecutingFrame<'_> { // arg1 = orig (original exception) // arg2 = excs (list of exceptions raised/reraised in except* blocks) // Returns: exception to reraise, or None if nothing to reraise - crate::exceptions::prep_reraise_star(arg1, arg2, vm) + crate::exceptions::prep_reraise_star(&arg1, &arg2, vm) } } } diff --git a/crates/vm/src/function/argument.rs b/crates/vm/src/function/argument.rs index e8dabc3f1..589422aa1 100644 --- a/crates/vm/src/function/argument.rs +++ b/crates/vm/src/function/argument.rs @@ -1,6 +1,6 @@ use crate::{ - AsObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, - builtins::{PyBaseExceptionRef, PyTupleRef, PyTypeRef}, + AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, + builtins::{PyBaseExceptionRef, PyTupleRef, PyType}, common::wtf8::{Wtf8, Wtf8Buf}, convert::ToPyObject, object::{Traverse, TraverseFn}, @@ -221,11 +221,11 @@ impl FuncArgs { } #[must_use] - pub fn get_kwarg(&self, key: &str, default: PyObjectRef) -> PyObjectRef { + pub fn get_kwarg(&self, key: &str, default: &PyObject) -> PyObjectRef { self.kwargs .get(key) .cloned() - .unwrap_or_else(|| default.clone()) + .unwrap_or_else(|| default.to_owned()) } #[must_use] @@ -236,12 +236,12 @@ impl FuncArgs { pub fn get_optional_kwarg_with_type( &self, key: &str, - ty: PyTypeRef, + ty: &Py, vm: &VirtualMachine, ) -> PyResult> { match self.get_optional_kwarg(key) { Some(kwarg) => { - if kwarg.fast_isinstance(&ty) { + if kwarg.fast_isinstance(ty) { Ok(Some(kwarg)) } else { let expected_ty_name = &ty.name(); diff --git a/crates/vm/src/import.rs b/crates/vm/src/import.rs index 984ea6716..dce9f9781 100644 --- a/crates/vm/src/import.rs +++ b/crates/vm/src/import.rs @@ -35,7 +35,7 @@ pub(crate) fn init_importlib_base(vm: &mut VirtualMachine) -> PyResult PyResult<()> { +pub(crate) fn init_importlib_package(vm: &VirtualMachine, importlib: &PyObject) -> PyResult<()> { use crate::{TryFromObject, builtins::PyListRef}; thread::enter_vm(vm, || { diff --git a/crates/vm/src/stdlib/_ast.rs b/crates/vm/src/stdlib/_ast.rs index ea44eff81..eaf9cb1cc 100644 --- a/crates/vm/src/stdlib/_ast.rs +++ b/crates/vm/src/stdlib/_ast.rs @@ -279,17 +279,18 @@ fn get_int_field( field: &'static str, typ: &str, ) -> PyResult { - node_object_to_i32(vm, get_node_field(vm, obj, field, typ)?) + let value = get_node_field(vm, obj, field, typ)?; + node_object_to_i32(vm, &value) } -pub(super) fn node_object_to_i32(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { +pub(super) fn node_object_to_i32(vm: &VirtualMachine, obj: &PyObject) -> PyResult { if obj.is(&vm.ctx.true_value) { return Ok(1); } if obj.is(&vm.ctx.false_value) { return Ok(0); } - let int: PyRef = match obj.clone().try_into_value(vm) { + let int: PyRef = match obj.to_owned().try_into_value(vm) { Ok(int) => int, Err(_) => { return Err(vm.new_value_error(format!("invalid integer value: {}", obj.repr(vm)?))); @@ -408,7 +409,7 @@ fn get_opt_int_field( field: &'static str, ) -> PyResult> { match get_node_field_opt(vm, obj, field)? { - Some(val) => node_object_to_i32(vm, val).map(Some), + Some(val) => node_object_to_i32(vm, &val).map(Some), None => Ok(None), } } @@ -707,7 +708,7 @@ fn range_from_object( object: PyObjectRef, name: &str, ) -> PyResult { - range_from_object_impl(vm, source_file, object, name, false) + range_from_object_impl(vm, source_file, &object, name, false) } fn type_param_range_from_object( @@ -715,7 +716,7 @@ fn type_param_range_from_object( source_file: &SourceFile, object: PyObjectRef, ) -> PyResult { - range_from_object_impl(vm, source_file, object, "type_param", true) + range_from_object_impl(vm, source_file, &object, "type_param", true) } fn expr_range_from_object( @@ -723,7 +724,7 @@ fn expr_range_from_object( source_file: &SourceFile, object: PyObjectRef, ) -> PyResult { - range_from_object_impl(vm, source_file, object, "expr", false) + range_from_object_impl(vm, source_file, &object, "expr", false) } fn stmt_range_from_object( @@ -731,7 +732,7 @@ fn stmt_range_from_object( source_file: &SourceFile, object: PyObjectRef, ) -> PyResult { - range_from_object_impl(vm, source_file, object, "stmt", false) + range_from_object_impl(vm, source_file, &object, "stmt", false) } fn pattern_range_from_object( @@ -739,7 +740,7 @@ fn pattern_range_from_object( source_file: &SourceFile, object: PyObjectRef, ) -> PyResult { - range_from_object_impl(vm, source_file, object, "pattern", true) + range_from_object_impl(vm, source_file, &object, "pattern", true) } fn excepthandler_range_from_object( @@ -747,18 +748,18 @@ fn excepthandler_range_from_object( source_file: &SourceFile, object: PyObjectRef, ) -> PyResult { - range_from_object_impl(vm, source_file, object, "excepthandler", false) + range_from_object_impl(vm, source_file, &object, "excepthandler", false) } fn excepthandler_range_from_object_unvalidated( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, ) -> PyResult { - let start_row = get_int_field(vm, &object, "lineno", "excepthandler")?; - let start_column = get_int_field(vm, &object, "col_offset", "excepthandler")?; - let end_row = get_opt_int_field(vm, &object, "end_lineno")?.unwrap_or(start_row); - let end_column = get_opt_int_field(vm, &object, "end_col_offset")?.unwrap_or(start_column); + let start_row = get_int_field(vm, object, "lineno", "excepthandler")?; + let start_column = get_int_field(vm, object, "col_offset", "excepthandler")?; + let end_row = get_opt_int_field(vm, object, "end_lineno")?.unwrap_or(start_row); + let end_column = get_opt_int_field(vm, object, "end_col_offset")?.unwrap_or(start_column); let location = PySourceRange { start: PySourceLocation { @@ -788,21 +789,21 @@ fn excepthandler_range_from_object_unvalidated( fn range_from_object_impl( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, name: &str, end_required: bool, ) -> PyResult { - let start_row = get_int_field(vm, &object, "lineno", name)?; - let start_column = get_int_field(vm, &object, "col_offset", name)?; + let start_row = get_int_field(vm, object, "lineno", name)?; + let start_column = get_int_field(vm, object, "col_offset", name)?; let end_row = if end_required { - get_int_field(vm, &object, "end_lineno", name)? + get_int_field(vm, object, "end_lineno", name)? } else { - get_opt_int_field(vm, &object, "end_lineno")?.unwrap_or(start_row) + get_opt_int_field(vm, object, "end_lineno")?.unwrap_or(start_row) }; let end_column = if end_required { - get_int_field(vm, &object, "end_col_offset", name)? + get_int_field(vm, object, "end_col_offset", name)? } else { - get_opt_int_field(vm, &object, "end_col_offset")?.unwrap_or(start_column) + get_opt_int_field(vm, object, "end_col_offset")?.unwrap_or(start_column) }; // lineno=0 or negative values as a special case (no location info). @@ -1942,11 +1943,11 @@ pub(crate) fn parse( } #[cfg(feature = "parser")] -pub(crate) fn wrap_interactive(vm: &VirtualMachine, module_obj: PyObjectRef) -> PyResult { +pub(crate) fn wrap_interactive(vm: &VirtualMachine, module_obj: &PyObject) -> PyResult { if !module_obj.class().is(pyast::NodeModModule::static_type()) { return Err(vm.new_type_error("expected Module node")); } - let body = get_node_field(vm, &module_obj, "body", "Module")?; + let body = get_node_field(vm, module_obj, "body", "Module")?; let node = NodeAst .into_ref_with_type(vm, pyast::NodeModInteractive::static_type().to_owned()) .unwrap(); diff --git a/crates/vm/src/stdlib/_ast/basic.rs b/crates/vm/src/stdlib/_ast/basic.rs index c25dd3c55..e7143057b 100644 --- a/crates/vm/src/stdlib/_ast/basic.rs +++ b/crates/vm/src/stdlib/_ast/basic.rs @@ -49,6 +49,6 @@ impl Node for bool { _source_file: &SourceFile, object: PyObjectRef, ) -> PyResult { - node_object_to_i32(vm, object).map(|i| i != 0) + node_object_to_i32(vm, &object).map(|i| i != 0) } } diff --git a/crates/vm/src/stdlib/_ast/constant.rs b/crates/vm/src/stdlib/_ast/constant.rs index 189c1538d..5985a0017 100644 --- a/crates/vm/src/stdlib/_ast/constant.rs +++ b/crates/vm/src/stdlib/_ast/constant.rs @@ -139,7 +139,7 @@ pub(super) fn runtime_string_from_pyobject( vm: &VirtualMachine, object: PyObjectRef, ) -> (Option>, Option>) { - runtime_string_from_object(vm, object) + runtime_string_from_object(vm, &object) } pub(super) fn runtime_string_object( @@ -315,7 +315,7 @@ pub(super) fn constant_object_to_constant_data( fn runtime_string_from_object( vm: &VirtualMachine, - object: PyObjectRef, + object: &PyObject, ) -> (Option>, Option>) { if object.class().is(vm.ctx.types.str_type) { ( @@ -351,18 +351,21 @@ fn runtime_string_to_object( } } -fn first_invalid_constant_type(vm: &VirtualMachine, value_object: PyObjectRef) -> PyResult { +fn first_invalid_constant_type(vm: &VirtualMachine, value_object: &PyObject) -> PyResult { let cls = value_object.class(); let class_name = cls.name().to_owned(); if cls.is(vm.ctx.types.tuple_type) { vm.with_recursion(" during compilation", || { - let tuple = value_object.clone().downcast::().map_err(|obj| { - vm.new_type_error(format!( - "Expected type {}, not {}", - PyTuple::static_type().name(), - obj.class().name() - )) - })?; + let tuple = value_object + .to_owned() + .downcast::() + .map_err(|obj| { + vm.new_type_error(format!( + "Expected type {}, not {}", + PyTuple::static_type().name(), + obj.class().name() + )) + })?; for item in tuple.iter() { if let Some(invalid_type) = first_invalid_constant_type_opt(vm, item.clone())? { return Ok(invalid_type); @@ -372,7 +375,7 @@ fn first_invalid_constant_type(vm: &VirtualMachine, value_object: PyObjectRef) - }) } else if cls.is(vm.ctx.types.frozenset_type) { vm.with_recursion(" during compilation", || { - let set = value_object.clone().downcast::().unwrap(); + let set = value_object.to_owned().downcast::().unwrap(); for item in set.elements() { if let Some(invalid_type) = first_invalid_constant_type_opt(vm, item)? { return Ok(invalid_type); @@ -402,7 +405,7 @@ fn first_invalid_constant_type_opt( return Ok(None); } if cls.is(vm.ctx.types.tuple_type) || cls.is(vm.ctx.types.frozenset_type) { - return first_invalid_constant_type(vm, value_object).map(Some); + return first_invalid_constant_type(vm, &value_object).map(Some); } Ok(Some(cls.name().to_owned())) } @@ -440,19 +443,19 @@ fn constant_data_to_object(vm: &VirtualMachine, constant: ConstantData) -> PyObj pub(super) fn constant_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { - let value_object = get_node_field(vm, &object, "value", "Constant")?; + let value_object = get_node_field(vm, object, "value", "Constant")?; let (value, invalid_type) = match ConstantLiteral::ast_from_object(vm, source_file, value_object.clone()) { Ok(value) => (value, None), Err(_) => ( ConstantLiteral::None, - Some(first_invalid_constant_type(vm, value_object)?), + Some(first_invalid_constant_type(vm, &value_object)?), ), }; - let kind = get_node_field_opt(vm, &object, "kind")? + let kind = get_node_field_opt(vm, object, "kind")? .map(|object| { if !object.class().is(vm.ctx.types.str_type) { return Err(vm.new_type_error("AST string must be of type str")); @@ -497,7 +500,7 @@ impl Node for Constant { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Constant")?; - constant_from_object_with_range(vm, source_file, object, range) + constant_from_object_with_range(vm, source_file, &object, range) } } diff --git a/crates/vm/src/stdlib/_ast/elif_else_clause.rs b/crates/vm/src/stdlib/_ast/elif_else_clause.rs index 2097c349c..ca8187bf3 100644 --- a/crates/vm/src/stdlib/_ast/elif_else_clause.rs +++ b/crates/vm/src/stdlib/_ast/elif_else_clause.rs @@ -64,13 +64,13 @@ pub(super) fn ast_to_object( pub(super) fn ast_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { - let test = get_required_node_field(vm, source_file, &object, "test", "If")?; - let body: Vec> = get_node_list_field(vm, source_file, &object, "body", "If")?; + let test = get_required_node_field(vm, source_file, object, "test", "If")?; + let body: Vec> = get_node_list_field(vm, source_file, object, "body", "If")?; let orelse: Vec> = - get_node_list_field(vm, source_file, &object, "orelse", "If")?; + get_node_list_field(vm, source_file, object, "orelse", "If")?; let runtime_body = runtime_stmt_list_metadata(&body); let runtime_orelse = runtime_stmt_list_metadata(&orelse); let body = lower_runtime_stmt_list(body); diff --git a/crates/vm/src/stdlib/_ast/exception.rs b/crates/vm/src/stdlib/_ast/exception.rs index aee577098..e09f52e40 100644 --- a/crates/vm/src/stdlib/_ast/exception.rs +++ b/crates/vm/src/stdlib/_ast/exception.rs @@ -34,7 +34,7 @@ impl Node for ast::ExceptHandler { Ok(Self::ExceptHandler(except_handler_from_object_with_range( vm, source_file, - object, + &object, range, )?)) } @@ -44,18 +44,18 @@ impl Node for ast::ExceptHandler { fn except_handler_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let body: Vec> = - get_node_list_field(vm, source_file, &object, "body", "ExceptHandler")?; + get_node_list_field(vm, source_file, object, "body", "ExceptHandler")?; let (runtime_body, body) = runtime_stmt_list_from_values(body); Ok(ast::ExceptHandlerExceptHandler { node_index: Default::default(), - type_: get_node_field_opt(vm, &object, "type")? + type_: get_node_field_opt(vm, object, "type")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - name: get_node_field_opt(vm, &object, "name")? + name: get_node_field_opt(vm, object, "name")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, body, @@ -70,9 +70,9 @@ pub(super) fn except_handler_from_object_unvalidated_range( object: PyObjectRef, ) -> PyResult { ensure_excepthandler_node(vm, &object)?; - let range = excepthandler_range_from_object_unvalidated(vm, source_file, object.clone())?; + let range = excepthandler_range_from_object_unvalidated(vm, source_file, &object)?; Ok(ast::ExceptHandler::ExceptHandler( - except_handler_from_object_with_range(vm, source_file, object, range)?, + except_handler_from_object_with_range(vm, source_file, &object, range)?, )) } @@ -112,6 +112,6 @@ impl Node for ast::ExceptHandlerExceptHandler { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "ExceptHandler")?; - except_handler_from_object_with_range(vm, source_file, object, range) + except_handler_from_object_with_range(vm, source_file, &object, range) } } diff --git a/crates/vm/src/stdlib/_ast/expression.rs b/crates/vm/src/stdlib/_ast/expression.rs index 7c64e4f79..1334b8132 100644 --- a/crates/vm/src/stdlib/_ast/expression.rs +++ b/crates/vm/src/stdlib/_ast/expression.rs @@ -163,172 +163,176 @@ impl Node for ast::Expr { ExprKind::BoolOp => Self::BoolOp(expr_bool_op_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Named => Self::Named(expr_named_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::BinOp => Self::BinOp(expr_bin_op_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::UnaryOp => Self::UnaryOp(expr_unary_op_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Lambda => Self::Lambda(expr_lambda_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::If => Self::If(expr_if_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Dict => Self::Dict(expr_dict_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Set => Self::Set(expr_set_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::ListComp => Self::ListComp(expr_list_comp_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::SetComp => Self::SetComp(expr_set_comp_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::DictComp => Self::DictComp(expr_dict_comp_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Generator => Self::Generator(expr_generator_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Await => Self::Await(expr_await_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Yield => Self::Yield(expr_yield_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::YieldFrom => Self::YieldFrom(expr_yield_from_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Compare => Self::Compare(expr_compare_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Call => Self::Call(expr_call_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::FormattedValue => { - let formatted = - string::formatted_value_from_object_with_range(vm, source_file, object, range)?; + let formatted = string::formatted_value_from_object_with_range( + vm, + source_file, + &object, + range, + )?; string::formatted_value_to_expr(true, formatted) } ExprKind::Interpolation => { let interpolation = string::tstring_interpolation_from_object_with_range( vm, source_file, - object, + &object, range, )?; string::interpolation_to_expr(vm, source_file, interpolation)? } ExprKind::JoinedStr => { - string::joined_str_from_object_with_range(vm, source_file, object, range)? + string::joined_str_from_object_with_range(vm, source_file, &object, range)? .into_expr(true) } ExprKind::TemplateStr => { let template = - string::template_str_from_object_with_range(vm, source_file, object, range)?; + string::template_str_from_object_with_range(vm, source_file, &object, range)?; string::template_str_to_expr(vm, source_file, template)? } ExprKind::Constant => { - constant::constant_from_object_with_range(vm, source_file, object, range)? + constant::constant_from_object_with_range(vm, source_file, &object, range)? .into_expr() } ExprKind::Attribute => Self::Attribute(expr_attribute_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Subscript => Self::Subscript(expr_subscript_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Starred => Self::Starred(expr_starred_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Name => Self::Name(expr_name_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::List => Self::List(expr_list_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Tuple => Self::Tuple(expr_tuple_from_object_with_range( vm, source_file, - object, + &object, range, )?), ExprKind::Slice => Self::Slice(expr_slice_from_object_with_range( vm, source_file, - object, + &object, range, )?), }) @@ -339,18 +343,18 @@ impl Node for ast::Expr { fn expr_bool_op_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let values: Vec> = - get_node_list_field(vm, source_file, &object, "values", "BoolOp")?; + get_node_list_field(vm, source_file, object, "values", "BoolOp")?; let (runtime_values, values) = runtime_expr_list_from_values(values); Ok(ast::ExprBoolOp { node_index: Default::default(), op: Node::ast_from_object( vm, source_file, - get_node_field_required(vm, &object, "op", "BoolOp")?, + get_node_field_required(vm, object, "op", "BoolOp")?, )?, values, range, @@ -388,7 +392,7 @@ impl Node for ast::ExprBoolOp { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "BoolOp")?; - expr_bool_op_from_object_with_range(vm, source_file, object, range) + expr_bool_op_from_object_with_range(vm, source_file, &object, range) } } @@ -396,13 +400,13 @@ impl Node for ast::ExprBoolOp { fn expr_named_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprNamed { node_index: Default::default(), - target: get_required_node_field(vm, source_file, &object, "target", "NamedExpr")?, - value: get_required_node_field(vm, source_file, &object, "value", "NamedExpr")?, + target: get_required_node_field(vm, source_file, object, "target", "NamedExpr")?, + value: get_required_node_field(vm, source_file, object, "value", "NamedExpr")?, range, }) } @@ -433,7 +437,7 @@ impl Node for ast::ExprNamed { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "NamedExpr")?; - expr_named_from_object_with_range(vm, source_file, object, range) + expr_named_from_object_with_range(vm, source_file, &object, range) } } @@ -441,18 +445,18 @@ impl Node for ast::ExprNamed { fn expr_bin_op_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprBinOp { node_index: Default::default(), - left: get_required_node_field(vm, source_file, &object, "left", "BinOp")?, + left: get_required_node_field(vm, source_file, object, "left", "BinOp")?, op: Node::ast_from_object( vm, source_file, - get_node_field_required(vm, &object, "op", "BinOp")?, + get_node_field_required(vm, object, "op", "BinOp")?, )?, - right: get_required_node_field(vm, source_file, &object, "right", "BinOp")?, + right: get_required_node_field(vm, source_file, object, "right", "BinOp")?, range, }) } @@ -486,7 +490,7 @@ impl Node for ast::ExprBinOp { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "BinOp")?; - expr_bin_op_from_object_with_range(vm, source_file, object, range) + expr_bin_op_from_object_with_range(vm, source_file, &object, range) } } @@ -494,7 +498,7 @@ impl Node for ast::ExprBinOp { fn expr_unary_op_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprUnaryOp { @@ -502,9 +506,9 @@ fn expr_unary_op_from_object_with_range( op: Node::ast_from_object( vm, source_file, - get_node_field_required(vm, &object, "op", "UnaryOp")?, + get_node_field_required(vm, object, "op", "UnaryOp")?, )?, - operand: get_required_node_field(vm, source_file, &object, "operand", "UnaryOp")?, + operand: get_required_node_field(vm, source_file, object, "operand", "UnaryOp")?, range, }) } @@ -534,7 +538,7 @@ impl Node for ast::ExprUnaryOp { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "UnaryOp")?; - expr_unary_op_from_object_with_range(vm, source_file, object, range) + expr_unary_op_from_object_with_range(vm, source_file, &object, range) } } @@ -542,7 +546,7 @@ impl Node for ast::ExprUnaryOp { fn expr_lambda_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprLambda { @@ -550,9 +554,9 @@ fn expr_lambda_from_object_with_range( parameters: Node::ast_from_object( vm, source_file, - get_node_field_required(vm, &object, "args", "Lambda")?, + get_node_field_required(vm, object, "args", "Lambda")?, )?, - body: get_required_node_field(vm, source_file, &object, "body", "Lambda")?, + body: get_required_node_field(vm, source_file, object, "body", "Lambda")?, range, }) } @@ -586,7 +590,7 @@ impl Node for ast::ExprLambda { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Lambda")?; - expr_lambda_from_object_with_range(vm, source_file, object, range) + expr_lambda_from_object_with_range(vm, source_file, &object, range) } } @@ -594,14 +598,14 @@ impl Node for ast::ExprLambda { fn expr_if_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprIf { node_index: Default::default(), - test: get_required_node_field(vm, source_file, &object, "test", "IfExp")?, - body: get_required_node_field(vm, source_file, &object, "body", "IfExp")?, - orelse: get_required_node_field(vm, source_file, &object, "orelse", "IfExp")?, + test: get_required_node_field(vm, source_file, object, "test", "IfExp")?, + body: get_required_node_field(vm, source_file, object, "body", "IfExp")?, + orelse: get_required_node_field(vm, source_file, object, "orelse", "IfExp")?, range, }) } @@ -635,7 +639,7 @@ impl Node for ast::ExprIf { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "IfExp")?; - expr_if_from_object_with_range(vm, source_file, object, range) + expr_if_from_object_with_range(vm, source_file, &object, range) } } @@ -643,13 +647,13 @@ impl Node for ast::ExprIf { fn expr_dict_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let keys: Vec> = - get_node_list_field(vm, source_file, &object, "keys", "Dict")?; + get_node_list_field(vm, source_file, object, "keys", "Dict")?; let values: Vec> = - get_node_list_field(vm, source_file, &object, "values", "Dict")?; + get_node_list_field(vm, source_file, object, "values", "Dict")?; if keys.len() != values.len() { return Err(vm.new_value_error("Dict doesn't have the same number of keys as values")); } @@ -704,7 +708,7 @@ impl Node for ast::ExprDict { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Dict")?; - expr_dict_from_object_with_range(vm, source_file, object, range) + expr_dict_from_object_with_range(vm, source_file, &object, range) } } @@ -712,11 +716,10 @@ impl Node for ast::ExprDict { fn expr_set_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { - let elts: Vec> = - get_node_list_field(vm, source_file, &object, "elts", "Set")?; + let elts: Vec> = get_node_list_field(vm, source_file, object, "elts", "Set")?; let (runtime_elts, elts) = runtime_expr_list_from_values(elts); Ok(ast::ExprSet { node_index: Default::default(), @@ -752,7 +755,7 @@ impl Node for ast::ExprSet { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Set")?; - expr_set_from_object_with_range(vm, source_file, object, range) + expr_set_from_object_with_range(vm, source_file, &object, range) } } @@ -760,13 +763,13 @@ impl Node for ast::ExprSet { fn expr_list_comp_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprListComp { node_index: Default::default(), - elt: get_required_node_field(vm, source_file, &object, "elt", "ListComp")?, - generators: get_node_list_field(vm, source_file, &object, "generators", "ListComp")?, + elt: get_required_node_field(vm, source_file, object, "elt", "ListComp")?, + generators: get_node_list_field(vm, source_file, object, "generators", "ListComp")?, range, }) } @@ -797,7 +800,7 @@ impl Node for ast::ExprListComp { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "ListComp")?; - expr_list_comp_from_object_with_range(vm, source_file, object, range) + expr_list_comp_from_object_with_range(vm, source_file, &object, range) } } @@ -805,13 +808,13 @@ impl Node for ast::ExprListComp { fn expr_set_comp_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprSetComp { node_index: Default::default(), - elt: get_required_node_field(vm, source_file, &object, "elt", "SetComp")?, - generators: get_node_list_field(vm, source_file, &object, "generators", "SetComp")?, + elt: get_required_node_field(vm, source_file, object, "elt", "SetComp")?, + generators: get_node_list_field(vm, source_file, object, "generators", "SetComp")?, range, }) } @@ -842,7 +845,7 @@ impl Node for ast::ExprSetComp { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "SetComp")?; - expr_set_comp_from_object_with_range(vm, source_file, object, range) + expr_set_comp_from_object_with_range(vm, source_file, &object, range) } } @@ -850,7 +853,7 @@ impl Node for ast::ExprSetComp { fn expr_dict_comp_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprDictComp { @@ -858,12 +861,12 @@ fn expr_dict_comp_from_object_with_range( key: Some(get_required_node_field( vm, source_file, - &object, + object, "key", "DictComp", )?), - value: get_required_node_field(vm, source_file, &object, "value", "DictComp")?, - generators: get_node_list_field(vm, source_file, &object, "generators", "DictComp")?, + value: get_required_node_field(vm, source_file, object, "value", "DictComp")?, + generators: get_node_list_field(vm, source_file, object, "generators", "DictComp")?, range, }) } @@ -897,7 +900,7 @@ impl Node for ast::ExprDictComp { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "DictComp")?; - expr_dict_comp_from_object_with_range(vm, source_file, object, range) + expr_dict_comp_from_object_with_range(vm, source_file, &object, range) } } @@ -905,13 +908,13 @@ impl Node for ast::ExprDictComp { fn expr_generator_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprGenerator { node_index: Default::default(), - elt: get_required_node_field(vm, source_file, &object, "elt", "GeneratorExp")?, - generators: get_node_list_field(vm, source_file, &object, "generators", "GeneratorExp")?, + elt: get_required_node_field(vm, source_file, object, "elt", "GeneratorExp")?, + generators: get_node_list_field(vm, source_file, object, "generators", "GeneratorExp")?, range, parenthesized: true, }) @@ -944,7 +947,7 @@ impl Node for ast::ExprGenerator { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "GeneratorExp")?; - expr_generator_from_object_with_range(vm, source_file, object, range) + expr_generator_from_object_with_range(vm, source_file, &object, range) } } @@ -952,12 +955,12 @@ impl Node for ast::ExprGenerator { fn expr_await_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprAwait { node_index: Default::default(), - value: get_required_node_field(vm, source_file, &object, "value", "Await")?, + value: get_required_node_field(vm, source_file, object, "value", "Await")?, range, }) } @@ -984,7 +987,7 @@ impl Node for ast::ExprAwait { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Await")?; - expr_await_from_object_with_range(vm, source_file, object, range) + expr_await_from_object_with_range(vm, source_file, &object, range) } } @@ -992,12 +995,12 @@ impl Node for ast::ExprAwait { fn expr_yield_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprYield { node_index: Default::default(), - value: get_node_field_opt(vm, &object, "value")? + value: get_node_field_opt(vm, object, "value")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, range, @@ -1027,7 +1030,7 @@ impl Node for ast::ExprYield { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Yield")?; - expr_yield_from_object_with_range(vm, source_file, object, range) + expr_yield_from_object_with_range(vm, source_file, &object, range) } } @@ -1035,12 +1038,12 @@ impl Node for ast::ExprYield { fn expr_yield_from_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprYieldFrom { node_index: Default::default(), - value: get_required_node_field(vm, source_file, &object, "value", "YieldFrom")?, + value: get_required_node_field(vm, source_file, object, "value", "YieldFrom")?, range, }) } @@ -1068,7 +1071,7 @@ impl Node for ast::ExprYieldFrom { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "YieldFrom")?; - expr_yield_from_from_object_with_range(vm, source_file, object, range) + expr_yield_from_from_object_with_range(vm, source_file, &object, range) } } @@ -1076,16 +1079,16 @@ impl Node for ast::ExprYieldFrom { fn expr_compare_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let comparators: Vec> = - get_node_list_field(vm, source_file, &object, "comparators", "Compare")?; + get_node_list_field(vm, source_file, object, "comparators", "Compare")?; let (runtime_comparators, comparators) = runtime_expr_boxed_slice_from_values(comparators); Ok(ast::ExprCompare { node_index: Default::default(), - left: get_required_node_field(vm, source_file, &object, "left", "Compare")?, - ops: get_node_boxed_slice_field(vm, source_file, &object, "ops", "Compare")?, + left: get_required_node_field(vm, source_file, object, "left", "Compare")?, + ops: get_node_boxed_slice_field(vm, source_file, object, "ops", "Compare")?, comparators, range, runtime_comparators, @@ -1125,7 +1128,7 @@ impl Node for ast::ExprCompare { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Compare")?; - expr_compare_from_object_with_range(vm, source_file, object, range) + expr_compare_from_object_with_range(vm, source_file, &object, range) } } @@ -1133,17 +1136,17 @@ impl Node for ast::ExprCompare { fn expr_call_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let mut arguments = merge_function_call_arguments( - PositionalArguments::ast_from_field(vm, source_file, &object, "args", "Call")?, - KeywordArguments::ast_from_field(vm, source_file, &object, "keywords", "Call")?, + PositionalArguments::ast_from_field(vm, source_file, object, "args", "Call")?, + KeywordArguments::ast_from_field(vm, source_file, object, "keywords", "Call")?, ); arguments.range = range; Ok(ast::ExprCall { node_index: Default::default(), - func: get_required_node_field(vm, source_file, &object, "func", "Call")?, + func: get_required_node_field(vm, source_file, object, "func", "Call")?, arguments, range_start: range.start(), }) @@ -1187,7 +1190,7 @@ impl Node for ast::ExprCall { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Call")?; - expr_call_from_object_with_range(vm, source_file, object, range) + expr_call_from_object_with_range(vm, source_file, &object, range) } } @@ -1195,17 +1198,17 @@ impl Node for ast::ExprCall { fn expr_attribute_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprAttribute { node_index: Default::default(), - value: get_required_node_field(vm, source_file, &object, "value", "Attribute")?, - attr: get_required_identifier_field(vm, source_file, &object, "attr", "Attribute")?, + value: get_required_node_field(vm, source_file, object, "value", "Attribute")?, + attr: get_required_identifier_field(vm, source_file, object, "attr", "Attribute")?, ctx: Node::ast_from_object( vm, source_file, - get_node_field_required(vm, &object, "ctx", "Attribute")?, + get_node_field_required(vm, object, "ctx", "Attribute")?, )?, range, }) @@ -1240,7 +1243,7 @@ impl Node for ast::ExprAttribute { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Attribute")?; - expr_attribute_from_object_with_range(vm, source_file, object, range) + expr_attribute_from_object_with_range(vm, source_file, &object, range) } } @@ -1248,17 +1251,17 @@ impl Node for ast::ExprAttribute { fn expr_subscript_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprSubscript { node_index: Default::default(), - value: get_required_node_field(vm, source_file, &object, "value", "Subscript")?, - slice: get_required_node_field(vm, source_file, &object, "slice", "Subscript")?, + value: get_required_node_field(vm, source_file, object, "value", "Subscript")?, + slice: get_required_node_field(vm, source_file, object, "slice", "Subscript")?, ctx: Node::ast_from_object( vm, source_file, - get_node_field_required(vm, &object, "ctx", "Subscript")?, + get_node_field_required(vm, object, "ctx", "Subscript")?, )?, range, }) @@ -1292,7 +1295,7 @@ impl Node for ast::ExprSubscript { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Subscript")?; - expr_subscript_from_object_with_range(vm, source_file, object, range) + expr_subscript_from_object_with_range(vm, source_file, &object, range) } } @@ -1300,16 +1303,16 @@ impl Node for ast::ExprSubscript { fn expr_starred_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprStarred { node_index: Default::default(), - value: get_required_node_field(vm, source_file, &object, "value", "Starred")?, + value: get_required_node_field(vm, source_file, object, "value", "Starred")?, ctx: Node::ast_from_object( vm, source_file, - get_node_field_required(vm, &object, "ctx", "Starred")?, + get_node_field_required(vm, object, "ctx", "Starred")?, )?, range, }) @@ -1340,7 +1343,7 @@ impl Node for ast::ExprStarred { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Starred")?; - expr_starred_from_object_with_range(vm, source_file, object, range) + expr_starred_from_object_with_range(vm, source_file, &object, range) } } @@ -1348,16 +1351,16 @@ impl Node for ast::ExprStarred { fn expr_name_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprName { node_index: Default::default(), - id: get_required_identifier_field(vm, source_file, &object, "id", "Name")?, + id: get_required_identifier_field(vm, source_file, object, "id", "Name")?, ctx: Node::ast_from_object( vm, source_file, - get_node_field_required(vm, &object, "ctx", "Name")?, + get_node_field_required(vm, object, "ctx", "Name")?, )?, range, }) @@ -1389,7 +1392,7 @@ impl Node for ast::ExprName { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Name")?; - expr_name_from_object_with_range(vm, source_file, object, range) + expr_name_from_object_with_range(vm, source_file, &object, range) } } @@ -1397,11 +1400,11 @@ impl Node for ast::ExprName { fn expr_list_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let elts: Vec> = - get_node_list_field(vm, source_file, &object, "elts", "List")?; + get_node_list_field(vm, source_file, object, "elts", "List")?; let (runtime_elts, elts) = runtime_expr_list_from_values(elts); Ok(ast::ExprList { node_index: Default::default(), @@ -1409,7 +1412,7 @@ fn expr_list_from_object_with_range( ctx: Node::ast_from_object( vm, source_file, - get_node_field_required(vm, &object, "ctx", "List")?, + get_node_field_required(vm, object, "ctx", "List")?, )?, range, runtime_elts, @@ -1446,7 +1449,7 @@ impl Node for ast::ExprList { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "List")?; - expr_list_from_object_with_range(vm, source_file, object, range) + expr_list_from_object_with_range(vm, source_file, &object, range) } } @@ -1454,11 +1457,11 @@ impl Node for ast::ExprList { fn expr_tuple_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let elts: Vec> = - get_node_list_field(vm, source_file, &object, "elts", "Tuple")?; + get_node_list_field(vm, source_file, object, "elts", "Tuple")?; let (runtime_elts, elts) = runtime_expr_list_from_values(elts); Ok(ast::ExprTuple { node_index: Default::default(), @@ -1466,7 +1469,7 @@ fn expr_tuple_from_object_with_range( ctx: Node::ast_from_object( vm, source_file, - get_node_field_required(vm, &object, "ctx", "Tuple")?, + get_node_field_required(vm, object, "ctx", "Tuple")?, )?, range, parenthesized: true, @@ -1505,7 +1508,7 @@ impl Node for ast::ExprTuple { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Tuple")?; - expr_tuple_from_object_with_range(vm, source_file, object, range) + expr_tuple_from_object_with_range(vm, source_file, &object, range) } } @@ -1513,18 +1516,18 @@ impl Node for ast::ExprTuple { fn expr_slice_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::ExprSlice { node_index: Default::default(), - lower: get_node_field_opt(vm, &object, "lower")? + lower: get_node_field_opt(vm, object, "lower")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - upper: get_node_field_opt(vm, &object, "upper")? + upper: get_node_field_opt(vm, object, "upper")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - step: get_node_field_opt(vm, &object, "step")? + step: get_node_field_opt(vm, object, "step")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, range, @@ -1560,7 +1563,7 @@ impl Node for ast::ExprSlice { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Slice")?; - expr_slice_from_object_with_range(vm, source_file, object, range) + expr_slice_from_object_with_range(vm, source_file, &object, range) } } @@ -1641,10 +1644,8 @@ impl Node for ast::Comprehension { ) -> PyResult { let ifs: Vec> = get_node_list_field(vm, source_file, &object, "ifs", "comprehension")?; - let is_async = node_object_to_i32( - vm, - get_node_field(vm, &object, "is_async", "comprehension")?, - )?; + let is_async_obj = get_node_field(vm, &object, "is_async", "comprehension")?; + let is_async = node_object_to_i32(vm, &is_async_obj)?; let runtime_ifs = runtime_expr_list_metadata(&ifs); let runtime_is_async = (is_async != 0 && is_async != 1).then_some(is_async); Ok(Self { diff --git a/crates/vm/src/stdlib/_ast/other.rs b/crates/vm/src/stdlib/_ast/other.rs index 837c7d120..d943f7cf6 100644 --- a/crates/vm/src/stdlib/_ast/other.rs +++ b/crates/vm/src/stdlib/_ast/other.rs @@ -11,7 +11,7 @@ impl Node for ast::ConversionFlag { _source_file: &SourceFile, object: PyObjectRef, ) -> PyResult { - match node_object_to_i32(vm, object)? { + match node_object_to_i32(vm, &object)? { -1 => Ok(Self::None), x if x == b's' as i32 => Ok(Self::Str), x if x == b'r' as i32 => Ok(Self::Repr), diff --git a/crates/vm/src/stdlib/_ast/pattern.rs b/crates/vm/src/stdlib/_ast/pattern.rs index 7c834178b..f09db1023 100644 --- a/crates/vm/src/stdlib/_ast/pattern.rs +++ b/crates/vm/src/stdlib/_ast/pattern.rs @@ -111,40 +111,40 @@ impl Node for ast::Pattern { PatternKind::Value => Self::MatchValue(pattern_match_value_from_object_with_range( vm, source_file, - object, + &object, range, )?), PatternKind::Singleton => Self::MatchSingleton( - pattern_match_singleton_from_object_with_range(vm, source_file, object, range)?, + pattern_match_singleton_from_object_with_range(vm, source_file, &object, range)?, ), PatternKind::Sequence => Self::MatchSequence( - pattern_match_sequence_from_object_with_range(vm, source_file, object, range)?, + pattern_match_sequence_from_object_with_range(vm, source_file, &object, range)?, ), PatternKind::Mapping => Self::MatchMapping( - pattern_match_mapping_from_object_with_range(vm, source_file, object, range)?, + pattern_match_mapping_from_object_with_range(vm, source_file, &object, range)?, ), PatternKind::Class => Self::MatchClass(pattern_match_class_from_object_with_range( vm, source_file, - object, + &object, range, )?), PatternKind::Star => Self::MatchStar(pattern_match_star_from_object_with_range( vm, source_file, - object, + &object, range, )?), PatternKind::As => Self::MatchAs(pattern_match_as_from_object_with_range( vm, source_file, - object, + &object, range, )?), PatternKind::Or => Self::MatchOr(pattern_match_or_from_object_with_range( vm, source_file, - object, + &object, range, )?), }) @@ -204,12 +204,12 @@ fn pattern_list_from_field( fn pattern_match_value_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::PatternMatchValue { node_index: Default::default(), - value: get_required_node_field(vm, source_file, &object, "value", "MatchValue")?, + value: get_required_node_field(vm, source_file, object, "value", "MatchValue")?, range, }) } @@ -237,7 +237,7 @@ impl Node for ast::PatternMatchValue { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "MatchValue")?; - pattern_match_value_from_object_with_range(vm, source_file, object, range) + pattern_match_value_from_object_with_range(vm, source_file, &object, range) } } @@ -245,7 +245,7 @@ impl Node for ast::PatternMatchValue { fn pattern_match_singleton_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::PatternMatchSingleton { @@ -253,7 +253,7 @@ fn pattern_match_singleton_from_object_with_range( value: Node::ast_from_object( vm, source_file, - get_node_field(vm, &object, "value", "MatchSingleton")?, + get_node_field(vm, object, "value", "MatchSingleton")?, )?, range, }) @@ -285,7 +285,7 @@ impl Node for ast::PatternMatchSingleton { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "MatchSingleton")?; - pattern_match_singleton_from_object_with_range(vm, source_file, object, range) + pattern_match_singleton_from_object_with_range(vm, source_file, &object, range) } } @@ -319,11 +319,11 @@ impl Node for ast::Singleton { fn pattern_match_sequence_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let (runtime_patterns, patterns) = - pattern_list_from_field(vm, source_file, &object, "patterns", "MatchSequence", range)?; + pattern_list_from_field(vm, source_file, object, "patterns", "MatchSequence", range)?; Ok(ast::PatternMatchSequence { node_index: Default::default(), patterns: patterns.to_vec(), @@ -362,7 +362,7 @@ impl Node for ast::PatternMatchSequence { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "MatchSequence")?; - pattern_match_sequence_from_object_with_range(vm, source_file, object, range) + pattern_match_sequence_from_object_with_range(vm, source_file, &object, range) } } @@ -370,13 +370,13 @@ impl Node for ast::PatternMatchSequence { fn pattern_match_mapping_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let keys: Vec> = - get_node_list_field(vm, source_file, &object, "keys", "MatchMapping")?; + get_node_list_field(vm, source_file, object, "keys", "MatchMapping")?; let patterns: Vec> = - get_node_list_field(vm, source_file, &object, "patterns", "MatchMapping")?; + get_node_list_field(vm, source_file, object, "patterns", "MatchMapping")?; let runtime_keys = keys.iter().any(Option::is_none).then(|| keys.clone()); let runtime_patterns = patterns .iter() @@ -386,7 +386,7 @@ fn pattern_match_mapping_from_object_with_range( node_index: Default::default(), keys: lower_nullable_exprs(&keys, range).into(), patterns: lower_nullable_patterns(&patterns, range).into(), - rest: get_node_field_opt(vm, &object, "rest")? + rest: get_node_field_opt(vm, object, "rest")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, range, @@ -432,7 +432,7 @@ impl Node for ast::PatternMatchMapping { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "MatchMapping")?; - pattern_match_mapping_from_object_with_range(vm, source_file, object, range) + pattern_match_mapping_from_object_with_range(vm, source_file, &object, range) } } @@ -440,21 +440,21 @@ impl Node for ast::PatternMatchMapping { fn pattern_match_class_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { - let cls = get_required_node_field(vm, source_file, &object, "cls", "MatchClass")?; + let cls = get_required_node_field(vm, source_file, object, "cls", "MatchClass")?; let patterns: Vec> = - get_node_list_field(vm, source_file, &object, "patterns", "MatchClass")?; + get_node_list_field(vm, source_file, object, "patterns", "MatchClass")?; let kwd_attrs = PatternMatchClassKeywordAttributes::ast_from_field( vm, source_file, - &object, + object, "kwd_attrs", "MatchClass", )?; let kwd_patterns: Vec> = - get_node_list_field(vm, source_file, &object, "kwd_patterns", "MatchClass")?; + get_node_list_field(vm, source_file, object, "kwd_patterns", "MatchClass")?; let has_runtime_shape = kwd_attrs.0.len() != kwd_patterns.len() || patterns.iter().any(Option::is_none) || kwd_patterns.iter().any(Option::is_none); @@ -529,7 +529,7 @@ impl Node for ast::PatternMatchClass { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "MatchClass")?; - pattern_match_class_from_object_with_range(vm, source_file, object, range) + pattern_match_class_from_object_with_range(vm, source_file, &object, range) } } @@ -602,12 +602,12 @@ impl Node for PatternMatchClassKeywordPatterns { fn pattern_match_star_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::PatternMatchStar { node_index: Default::default(), - name: get_node_field_opt(vm, &object, "name")? + name: get_node_field_opt(vm, object, "name")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, range, @@ -637,7 +637,7 @@ impl Node for ast::PatternMatchStar { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "MatchStar")?; - pattern_match_star_from_object_with_range(vm, source_file, object, range) + pattern_match_star_from_object_with_range(vm, source_file, &object, range) } } @@ -645,15 +645,15 @@ impl Node for ast::PatternMatchStar { fn pattern_match_as_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::PatternMatchAs { node_index: Default::default(), - pattern: get_node_field_opt(vm, &object, "pattern")? + pattern: get_node_field_opt(vm, object, "pattern")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - name: get_node_field_opt(vm, &object, "name")? + name: get_node_field_opt(vm, object, "name")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, range, @@ -686,7 +686,7 @@ impl Node for ast::PatternMatchAs { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "MatchAs")?; - pattern_match_as_from_object_with_range(vm, source_file, object, range) + pattern_match_as_from_object_with_range(vm, source_file, &object, range) } } @@ -694,11 +694,11 @@ impl Node for ast::PatternMatchAs { fn pattern_match_or_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let (runtime_patterns, patterns) = - pattern_list_from_field(vm, source_file, &object, "patterns", "MatchOr", range)?; + pattern_list_from_field(vm, source_file, object, "patterns", "MatchOr", range)?; Ok(ast::PatternMatchOr { node_index: Default::default(), patterns: patterns.to_vec(), @@ -733,7 +733,7 @@ impl Node for ast::PatternMatchOr { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "MatchOr")?; - pattern_match_or_from_object_with_range(vm, source_file, object, range) + pattern_match_or_from_object_with_range(vm, source_file, &object, range) } } diff --git a/crates/vm/src/stdlib/_ast/pyast.rs b/crates/vm/src/stdlib/_ast/pyast.rs index ebce1a788..987b28bd4 100644 --- a/crates/vm/src/stdlib/_ast/pyast.rs +++ b/crates/vm/src/stdlib/_ast/pyast.rs @@ -70,12 +70,12 @@ macro_rules! impl_base_node { impl $name { #[pymethod] fn __reduce__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { - super::python::_ast::ast_reduce(zelf, vm) + super::python::_ast::ast_reduce(&zelf, vm) } #[pymethod] fn __replace__(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - super::python::_ast::ast_replace(zelf, args, vm) + super::python::_ast::ast_replace(&zelf, args, vm) } #[extend_class] @@ -115,12 +115,12 @@ macro_rules! impl_base_node { impl $name { #[pymethod] fn __reduce__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { - super::python::_ast::ast_reduce(zelf, vm) + super::python::_ast::ast_reduce(&zelf, vm) } #[pymethod] fn __replace__(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - super::python::_ast::ast_replace(zelf, args, vm) + super::python::_ast::ast_replace(&zelf, args, vm) } #[extend_class] diff --git a/crates/vm/src/stdlib/_ast/python.rs b/crates/vm/src/stdlib/_ast/python.rs index 1b33e352d..89858a416 100644 --- a/crates/vm/src/stdlib/_ast/python.rs +++ b/crates/vm/src/stdlib/_ast/python.rs @@ -39,7 +39,7 @@ pub(crate) mod _ast { const AST_REDUCE: PyMethodDef = PyMethodDef::new_const( "__reduce__", |zelf: PyObjectRef, vm: &VirtualMachine| -> PyResult { - ast_reduce(zelf, vm) + ast_reduce(&zelf, vm) }, PyMethodFlags::METHOD, None, @@ -47,7 +47,7 @@ pub(crate) mod _ast { const AST_REPLACE: PyMethodDef = PyMethodDef::new_const( "__replace__", |zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine| -> PyResult { - ast_replace(zelf, args, vm) + ast_replace(&zelf, args, vm) }, PyMethodFlags::METHOD, None, @@ -55,7 +55,7 @@ pub(crate) mod _ast { const AST_DEEPCOPY: PyMethodDef = PyMethodDef::new_const( "__deepcopy__", |zelf: PyObjectRef, memo: PyObjectRef, vm: &VirtualMachine| -> PyResult { - ast_deepcopy(zelf, memo, vm) + ast_deepcopy(&zelf, &memo, vm) }, PyMethodFlags::METHOD, None, @@ -88,21 +88,21 @@ pub(crate) mod _ast { #[pymethod] fn __reduce__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { - ast_reduce(zelf, vm) + ast_reduce(&zelf, vm) } #[pymethod] fn __replace__(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - ast_replace(zelf, args, vm) + ast_replace(&zelf, args, vm) } #[pymethod] fn __deepcopy__(zelf: PyObjectRef, memo: PyObjectRef, vm: &VirtualMachine) -> PyResult { - ast_deepcopy(zelf, memo, vm) + ast_deepcopy(&zelf, &memo, vm) } } - pub(crate) fn ast_reduce(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { + pub(crate) fn ast_reduce(zelf: &PyObject, vm: &VirtualMachine) -> PyResult { let dict = zelf.as_object().dict(); let cls = zelf.class(); let type_obj: PyObjectRef = cls.to_owned().into(); @@ -213,7 +213,7 @@ pub(crate) mod _ast { obj.set_attr(&name, value, vm) } - pub(crate) fn ast_replace(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn ast_replace(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult { if !args.args.is_empty() { return Err(vm.new_type_error("__replace__() takes no positional arguments")); } @@ -298,13 +298,9 @@ pub(crate) mod _ast { Ok(result) } - pub(crate) fn ast_deepcopy( - zelf: PyObjectRef, - memo: PyObjectRef, - vm: &VirtualMachine, - ) -> PyResult { + pub(crate) fn ast_deepcopy(zelf: &PyObject, memo: &PyObject, vm: &VirtualMachine) -> PyResult { let memo_dict: PyDictRef = memo - .clone() + .to_owned() .downcast() .map_err(|_| vm.new_type_error("__deepcopy__() memo must be a dict"))?; let memo_key: PyObjectRef = vm.ctx.new_int(zelf.get_id() as i64).into(); @@ -330,7 +326,7 @@ pub(crate) mod _ast { if let (Some(src_dict), Some(dst_dict)) = (zelf.as_object().dict(), copied_dict) { let deepcopy = vm.import("copy", 0)?.get_attr("deepcopy", vm)?; for (key, value) in src_dict.items_vec() { - let copied_value = deepcopy.call((value, memo.clone()), vm)?; + let copied_value = deepcopy.call((value, memo.to_owned()), vm)?; dst_dict.set_item(&*key, copied_value, vm)?; } } @@ -598,7 +594,7 @@ This will become an error in Python 3.15.", const AST_REDUCE: PyMethodDef = PyMethodDef::new_const( "__reduce__", |zelf: PyObjectRef, vm: &VirtualMachine| -> PyResult { - ast_reduce(zelf, vm) + ast_reduce(&zelf, vm) }, PyMethodFlags::METHOD, None, @@ -606,7 +602,7 @@ This will become an error in Python 3.15.", const AST_REPLACE: PyMethodDef = PyMethodDef::new_const( "__replace__", |zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine| -> PyResult { - ast_replace(zelf, args, vm) + ast_replace(&zelf, args, vm) }, PyMethodFlags::METHOD, None, diff --git a/crates/vm/src/stdlib/_ast/statement.rs b/crates/vm/src/stdlib/_ast/statement.rs index 83eb15461..043c641a3 100644 --- a/crates/vm/src/stdlib/_ast/statement.rs +++ b/crates/vm/src/stdlib/_ast/statement.rs @@ -194,130 +194,136 @@ impl Node for ast::Stmt { }; let range = stmt_range_from_object(vm, source_file, object.clone())?; Ok(match kind { - StmtKind::FunctionDef { is_async } => Self::FunctionDef( - stmt_function_def_from_object_with_range(vm, source_file, object, range, is_async)?, - ), + StmtKind::FunctionDef { is_async } => { + Self::FunctionDef(stmt_function_def_from_object_with_range( + vm, + source_file, + &object, + range, + is_async, + )?) + } StmtKind::ClassDef => Self::ClassDef(stmt_class_def_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::Return => Self::Return(stmt_return_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::Delete => Self::Delete(stmt_delete_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::Assign => Self::Assign(stmt_assign_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::TypeAlias => Self::TypeAlias(stmt_type_alias_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::AugAssign => Self::AugAssign(stmt_aug_assign_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::AnnAssign => Self::AnnAssign(stmt_ann_assign_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::For { is_async } => Self::For(stmt_for_from_object_with_range( vm, source_file, - object, + &object, range, is_async, )?), StmtKind::While => Self::While(stmt_while_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::If => Self::If(elif_else_clause::ast_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::With { is_async } => Self::With(stmt_with_from_object_with_range( vm, source_file, - object, + &object, range, is_async, )?), StmtKind::Match => Self::Match(stmt_match_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::Raise => Self::Raise(stmt_raise_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::Try { is_star } => Self::Try(stmt_try_from_object_with_range( vm, source_file, - object, + &object, range, is_star, )?), StmtKind::Assert => Self::Assert(stmt_assert_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::Import => Self::Import(stmt_import_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::ImportFrom => Self::ImportFrom(stmt_import_from_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::Global => Self::Global(stmt_global_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::Nonlocal => Self::Nonlocal(stmt_nonlocal_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::Expr => Self::Expr(stmt_expr_from_object_with_range( vm, source_file, - object, + &object, range, )?), StmtKind::Pass => Self::Pass(stmt_pass_from_object_with_range(range)), @@ -331,7 +337,7 @@ impl Node for ast::Stmt { fn stmt_function_def_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, is_async: bool, ) -> PyResult { @@ -340,26 +346,26 @@ fn stmt_function_def_from_object_with_range( } else { "FunctionDef" }; - let name = get_required_identifier_field(vm, source_file, &object, "name", typ)?; + let name = get_required_identifier_field(vm, source_file, object, "name", typ)?; let parameters = Node::ast_from_object( vm, source_file, - get_node_field_required(vm, &object, "args", typ)?, + get_node_field_required(vm, object, "args", typ)?, )?; - let body: Vec> = get_node_list_field(vm, source_file, &object, "body", typ)?; + let body: Vec> = get_node_list_field(vm, source_file, object, "body", typ)?; let decorator_list: Vec> = - get_node_list_field(vm, source_file, &object, "decorator_list", typ)?; + get_node_list_field(vm, source_file, object, "decorator_list", typ)?; let runtime_decorator_exprs = runtime_decorator_expr_list(&decorator_list); let runtime_body = runtime_stmt_list_metadata(&body); let runtime_decorator_list = runtime_expr_list_metadata(&runtime_decorator_exprs); let body = lower_runtime_stmt_list(body); let decorator_list = lower_runtime_decorator_list(decorator_list); - let returns = get_node_field_opt(vm, &object, "returns")? + let returns = get_node_field_opt(vm, object, "returns")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?; let (runtime_type_comment, runtime_type_comment_bytes) = - runtime_stmt_type_comment(vm, get_ast_string_field_opt(vm, &object, "type_comment")?); - let type_params = type_params_from_field(vm, source_file, &object, "type_params", typ)?; + runtime_stmt_type_comment(vm, get_ast_string_field_opt(vm, object, "type_comment")?); + let type_params = type_params_from_field(vm, source_file, object, "type_params", typ)?; Ok(ast::StmtFunctionDef { node_index: Default::default(), name, @@ -461,7 +467,7 @@ impl Node for ast::StmtFunctionDef { "FunctionDef" }; let range = range_from_object(vm, source_file, _object.clone(), typ)?; - stmt_function_def_from_object_with_range(vm, source_file, _object, range, is_async) + stmt_function_def_from_object_with_range(vm, source_file, &_object, range, is_async) } } @@ -469,23 +475,23 @@ impl Node for ast::StmtFunctionDef { fn stmt_class_def_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { - let name = get_required_identifier_field(vm, source_file, &object, "name", "ClassDef")?; - let bases = PositionalArguments::ast_from_field(vm, source_file, &object, "bases", "ClassDef")?; + let name = get_required_identifier_field(vm, source_file, object, "name", "ClassDef")?; + let bases = PositionalArguments::ast_from_field(vm, source_file, object, "bases", "ClassDef")?; let keywords = - KeywordArguments::ast_from_field(vm, source_file, &object, "keywords", "ClassDef")?; + KeywordArguments::ast_from_field(vm, source_file, object, "keywords", "ClassDef")?; let body: Vec> = - get_node_list_field(vm, source_file, &object, "body", "ClassDef")?; + get_node_list_field(vm, source_file, object, "body", "ClassDef")?; let decorator_list: Vec> = - get_node_list_field(vm, source_file, &object, "decorator_list", "ClassDef")?; + get_node_list_field(vm, source_file, object, "decorator_list", "ClassDef")?; let runtime_decorator_exprs = runtime_decorator_expr_list(&decorator_list); let runtime_body = runtime_stmt_list_metadata(&body); let runtime_decorator_list = runtime_expr_list_metadata(&runtime_decorator_exprs); let body = lower_runtime_stmt_list(body); let decorator_list = lower_runtime_decorator_list(decorator_list); - let type_params = type_params_from_field(vm, source_file, &object, "type_params", "ClassDef")?; + let type_params = type_params_from_field(vm, source_file, object, "type_params", "ClassDef")?; Ok(ast::StmtClassDef { node_index: Default::default(), name, @@ -571,19 +577,19 @@ impl Node for ast::StmtClassDef { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "ClassDef")?; - stmt_class_def_from_object_with_range(vm, source_file, _object, range) + stmt_class_def_from_object_with_range(vm, source_file, &_object, range) } } // constructor fn stmt_return_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::StmtReturn { node_index: Default::default(), - value: get_node_field_opt(vm, &object, "value")? + value: get_node_field_opt(vm, object, "value")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, range, @@ -612,18 +618,18 @@ impl Node for ast::StmtReturn { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "Return")?; - stmt_return_from_object_with_range(vm, source_file, _object, range) + stmt_return_from_object_with_range(vm, source_file, &_object, range) } } // constructor fn stmt_delete_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let targets: Vec> = - get_node_list_field(vm, source_file, &object, "targets", "Delete")?; + get_node_list_field(vm, source_file, object, "targets", "Delete")?; let (runtime_targets, targets) = runtime_expr_list_from_values(targets); Ok(ast::StmtDelete { node_index: Default::default(), @@ -659,7 +665,7 @@ impl Node for ast::StmtDelete { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "Delete")?; - stmt_delete_from_object_with_range(vm, source_file, _object, range) + stmt_delete_from_object_with_range(vm, source_file, &_object, range) } } @@ -667,15 +673,15 @@ impl Node for ast::StmtDelete { fn stmt_assign_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let targets: Vec> = - get_node_list_field(vm, source_file, &object, "targets", "Assign")?; + get_node_list_field(vm, source_file, object, "targets", "Assign")?; let (runtime_targets, targets) = runtime_expr_list_from_values(targets); - let value = get_required_node_field(vm, source_file, &object, "value", "Assign")?; + let value = get_required_node_field(vm, source_file, object, "value", "Assign")?; let (runtime_type_comment, runtime_type_comment_bytes) = - runtime_stmt_type_comment(vm, get_ast_string_field_opt(vm, &object, "type_comment")?); + runtime_stmt_type_comment(vm, get_ast_string_field_opt(vm, object, "type_comment")?); Ok(ast::StmtAssign { node_index: Default::default(), targets, @@ -724,7 +730,7 @@ impl Node for ast::StmtAssign { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Assign")?; - stmt_assign_from_object_with_range(vm, source_file, object, range) + stmt_assign_from_object_with_range(vm, source_file, &object, range) } } @@ -732,14 +738,14 @@ impl Node for ast::StmtAssign { fn stmt_type_alias_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::StmtTypeAlias { node_index: Default::default(), - name: get_required_node_field(vm, source_file, &object, "name", "TypeAlias")?, - type_params: type_params_from_field(vm, source_file, &object, "type_params", "TypeAlias")?, - value: get_required_node_field(vm, source_file, &object, "value", "TypeAlias")?, + name: get_required_node_field(vm, source_file, object, "name", "TypeAlias")?, + type_params: type_params_from_field(vm, source_file, object, "type_params", "TypeAlias")?, + value: get_required_node_field(vm, source_file, object, "value", "TypeAlias")?, range, }) } @@ -780,7 +786,7 @@ impl Node for ast::StmtTypeAlias { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "TypeAlias")?; - stmt_type_alias_from_object_with_range(vm, source_file, _object, range) + stmt_type_alias_from_object_with_range(vm, source_file, &_object, range) } } @@ -788,18 +794,18 @@ impl Node for ast::StmtTypeAlias { fn stmt_aug_assign_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::StmtAugAssign { node_index: Default::default(), - target: get_required_node_field(vm, source_file, &object, "target", "AugAssign")?, + target: get_required_node_field(vm, source_file, object, "target", "AugAssign")?, op: Node::ast_from_object( vm, source_file, - get_node_field_required(vm, &object, "op", "AugAssign")?, + get_node_field_required(vm, object, "op", "AugAssign")?, )?, - value: get_required_node_field(vm, source_file, &object, "value", "AugAssign")?, + value: get_required_node_field(vm, source_file, object, "value", "AugAssign")?, range, }) } @@ -832,7 +838,7 @@ impl Node for ast::StmtAugAssign { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "AugAssign")?; - stmt_aug_assign_from_object_with_range(vm, source_file, _object, range) + stmt_aug_assign_from_object_with_range(vm, source_file, &_object, range) } } @@ -840,10 +846,11 @@ impl Node for ast::StmtAugAssign { fn stmt_ann_assign_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { - let simple = node_object_to_i32(vm, get_node_field(vm, &object, "simple", "AnnAssign")?)?; + let simple_obj = get_node_field(vm, object, "simple", "AnnAssign")?; + let simple = node_object_to_i32(vm, &simple_obj)?; let runtime_simple = if simple != 0 && simple != 1 { Some(simple) } else { @@ -851,9 +858,9 @@ fn stmt_ann_assign_from_object_with_range( }; Ok(ast::StmtAnnAssign { node_index: Default::default(), - target: get_required_node_field(vm, source_file, &object, "target", "AnnAssign")?, - annotation: get_required_node_field(vm, source_file, &object, "annotation", "AnnAssign")?, - value: get_node_field_opt(vm, &object, "value")? + target: get_required_node_field(vm, source_file, object, "target", "AnnAssign")?, + annotation: get_required_node_field(vm, source_file, object, "annotation", "AnnAssign")?, + value: get_node_field_opt(vm, object, "value")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, simple: simple != 0, @@ -897,7 +904,7 @@ impl Node for ast::StmtAnnAssign { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "AnnAssign")?; - stmt_ann_assign_from_object_with_range(vm, source_file, _object, range) + stmt_ann_assign_from_object_with_range(vm, source_file, &_object, range) } } @@ -905,22 +912,22 @@ impl Node for ast::StmtAnnAssign { fn stmt_for_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, is_async: bool, ) -> PyResult { let typ = if is_async { "AsyncFor" } else { "For" }; - let target = get_required_node_field(vm, source_file, &object, "target", typ)?; - let iter = get_required_node_field(vm, source_file, &object, "iter", typ)?; - let body: Vec> = get_node_list_field(vm, source_file, &object, "body", typ)?; + let target = get_required_node_field(vm, source_file, object, "target", typ)?; + let iter = get_required_node_field(vm, source_file, object, "iter", typ)?; + let body: Vec> = get_node_list_field(vm, source_file, object, "body", typ)?; let orelse: Vec> = - get_node_list_field(vm, source_file, &object, "orelse", typ)?; + get_node_list_field(vm, source_file, object, "orelse", typ)?; let runtime_body = runtime_stmt_list_metadata(&body); let runtime_orelse = runtime_stmt_list_metadata(&orelse); let body = lower_runtime_stmt_list(body); let orelse = lower_runtime_stmt_list(orelse); let (runtime_type_comment, runtime_type_comment_bytes) = - runtime_stmt_type_comment(vm, get_ast_string_field_opt(vm, &object, "type_comment")?); + runtime_stmt_type_comment(vm, get_ast_string_field_opt(vm, object, "type_comment")?); Ok(ast::StmtFor { node_index: Default::default(), target, @@ -996,7 +1003,7 @@ impl Node for ast::StmtFor { let is_async = is_node_instance(vm, &_object, pyast::NodeStmtAsyncFor::static_type())?; let typ = if is_async { "AsyncFor" } else { "For" }; let range = range_from_object(vm, source_file, _object.clone(), typ)?; - stmt_for_from_object_with_range(vm, source_file, _object, range, is_async) + stmt_for_from_object_with_range(vm, source_file, &_object, range, is_async) } } @@ -1004,18 +1011,18 @@ impl Node for ast::StmtFor { fn stmt_while_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let body: Vec> = - get_node_list_field(vm, source_file, &object, "body", "While")?; + get_node_list_field(vm, source_file, object, "body", "While")?; let orelse: Vec> = - get_node_list_field(vm, source_file, &object, "orelse", "While")?; + get_node_list_field(vm, source_file, object, "orelse", "While")?; let runtime_body = runtime_stmt_list_metadata(&body); let runtime_orelse = runtime_stmt_list_metadata(&orelse); Ok(ast::StmtWhile { node_index: Default::default(), - test: get_required_node_field(vm, source_file, &object, "test", "While")?, + test: get_required_node_field(vm, source_file, object, "test", "While")?, body: lower_runtime_stmt_list(body), orelse: lower_runtime_stmt_list(orelse), range, @@ -1061,7 +1068,7 @@ impl Node for ast::StmtWhile { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "While")?; - stmt_while_from_object_with_range(vm, source_file, _object, range) + stmt_while_from_object_with_range(vm, source_file, &_object, range) } } // constructor @@ -1095,23 +1102,23 @@ impl Node for ast::StmtIf { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "If")?; - elif_else_clause::ast_from_object_with_range(vm, source_file, object, range) + elif_else_clause::ast_from_object_with_range(vm, source_file, &object, range) } } // constructor fn stmt_with_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, is_async: bool, ) -> PyResult { let typ = if is_async { "AsyncWith" } else { "With" }; - let items = get_node_list_field(vm, source_file, &object, "items", typ)?; - let body: Vec> = get_node_list_field(vm, source_file, &object, "body", typ)?; + let items = get_node_list_field(vm, source_file, object, "items", typ)?; + let body: Vec> = get_node_list_field(vm, source_file, object, "body", typ)?; let (runtime_body, body) = runtime_stmt_list_from_values(body); let (runtime_type_comment, runtime_type_comment_bytes) = - runtime_stmt_type_comment(vm, get_ast_string_field_opt(vm, &object, "type_comment")?); + runtime_stmt_type_comment(vm, get_ast_string_field_opt(vm, object, "type_comment")?); Ok(ast::StmtWith { node_index: Default::default(), items, @@ -1173,20 +1180,20 @@ impl Node for ast::StmtWith { let is_async = is_node_instance(vm, &_object, pyast::NodeStmtAsyncWith::static_type())?; let typ = if is_async { "AsyncWith" } else { "With" }; let range = range_from_object(vm, source_file, _object.clone(), typ)?; - stmt_with_from_object_with_range(vm, source_file, _object, range, is_async) + stmt_with_from_object_with_range(vm, source_file, &_object, range, is_async) } } // constructor fn stmt_match_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::StmtMatch { node_index: Default::default(), - subject: get_required_node_field(vm, source_file, &object, "subject", "Match")?, - cases: get_node_list_field(vm, source_file, &object, "cases", "Match")?, + subject: get_required_node_field(vm, source_file, object, "subject", "Match")?, + cases: get_node_list_field(vm, source_file, object, "cases", "Match")?, range, }) } @@ -1216,22 +1223,22 @@ impl Node for ast::StmtMatch { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "Match")?; - stmt_match_from_object_with_range(vm, source_file, _object, range) + stmt_match_from_object_with_range(vm, source_file, &_object, range) } } // constructor fn stmt_raise_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::StmtRaise { node_index: Default::default(), - exc: get_node_field_opt(vm, &object, "exc")? + exc: get_node_field_opt(vm, object, "exc")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - cause: get_node_field_opt(vm, &object, "cause")? + cause: get_node_field_opt(vm, object, "cause")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, range, @@ -1263,25 +1270,25 @@ impl Node for ast::StmtRaise { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "Raise")?; - stmt_raise_from_object_with_range(vm, source_file, _object, range) + stmt_raise_from_object_with_range(vm, source_file, &_object, range) } } // constructor fn stmt_try_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, is_star: bool, ) -> PyResult { let typ = if is_star { "TryStar" } else { "Try" }; - let body: Vec> = get_node_list_field(vm, source_file, &object, "body", typ)?; + let body: Vec> = get_node_list_field(vm, source_file, object, "body", typ)?; let orelse: Vec> = - get_node_list_field(vm, source_file, &object, "orelse", typ)?; + get_node_list_field(vm, source_file, object, "orelse", typ)?; let finalbody: Vec> = - get_node_list_field(vm, source_file, &object, "finalbody", typ)?; + get_node_list_field(vm, source_file, object, "finalbody", typ)?; let (runtime_handler_values, handlers) = - except_handler_list_from_field(vm, source_file, &object, typ, is_star, range)?; + except_handler_list_from_field(vm, source_file, object, typ, is_star, range)?; let runtime_body = runtime_stmt_list_metadata(&body); let runtime_orelse = runtime_stmt_list_metadata(&orelse); let runtime_finalbody = runtime_stmt_list_metadata(&finalbody); @@ -1417,7 +1424,7 @@ impl Node for ast::StmtTry { ); let typ = if is_star { "TryStar" } else { "Try" }; let range = range_from_object(vm, source_file, _object.clone(), typ)?; - stmt_try_from_object_with_range(vm, source_file, _object, range, is_star) + stmt_try_from_object_with_range(vm, source_file, &_object, range, is_star) } } @@ -1425,13 +1432,13 @@ impl Node for ast::StmtTry { fn stmt_assert_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::StmtAssert { node_index: Default::default(), - test: get_required_node_field(vm, source_file, &object, "test", "Assert")?, - msg: get_node_field_opt(vm, &object, "msg")? + test: get_required_node_field(vm, source_file, object, "test", "Assert")?, + msg: get_node_field_opt(vm, object, "msg")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, range, @@ -1463,19 +1470,19 @@ impl Node for ast::StmtAssert { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "Assert")?; - stmt_assert_from_object_with_range(vm, source_file, _object, range) + stmt_assert_from_object_with_range(vm, source_file, &_object, range) } } // constructor fn stmt_import_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::StmtImport { node_index: Default::default(), - names: get_node_list_field(vm, source_file, &object, "names", "Import")?, + names: get_node_list_field(vm, source_file, object, "names", "Import")?, range, is_lazy: false, }) @@ -1505,24 +1512,24 @@ impl Node for ast::StmtImport { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "Import")?; - stmt_import_from_object_with_range(vm, source_file, _object, range) + stmt_import_from_object_with_range(vm, source_file, &_object, range) } } // constructor fn stmt_import_from_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { - let (level, raw_level) = import_from_level_from_field(vm, &object)?; + let (level, raw_level) = import_from_level_from_field(vm, object)?; let runtime_level = raw_level.filter(|level| *level < 0); Ok(ast::StmtImportFrom { node_index: Default::default(), - module: get_node_field_opt(vm, &object, "module")? + module: get_node_field_opt(vm, object, "module")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - names: get_node_list_field(vm, source_file, &object, "names", "ImportFrom")?, + names: get_node_list_field(vm, source_file, object, "names", "ImportFrom")?, level, range, is_lazy: false, @@ -1538,7 +1545,7 @@ fn import_from_level_from_field( return Ok((0, None)); }; let level = vm.with_recursion(" while traversing 'ImportFrom' node", || { - node_object_to_i32(vm, value) + node_object_to_i32(vm, &value) })?; if level < 0 { return Ok((0, Some(level))); @@ -1580,19 +1587,19 @@ impl Node for ast::StmtImportFrom { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "ImportFrom")?; - stmt_import_from_from_object_with_range(vm, source_file, _object, range) + stmt_import_from_from_object_with_range(vm, source_file, &_object, range) } } // constructor fn stmt_global_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::StmtGlobal { node_index: Default::default(), - names: get_node_list_field(vm, source_file, &object, "names", "Global")?, + names: get_node_list_field(vm, source_file, object, "names", "Global")?, range, }) } @@ -1619,19 +1626,19 @@ impl Node for ast::StmtGlobal { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "Global")?; - stmt_global_from_object_with_range(vm, source_file, _object, range) + stmt_global_from_object_with_range(vm, source_file, &_object, range) } } // constructor fn stmt_nonlocal_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::StmtNonlocal { node_index: Default::default(), - names: get_node_list_field(vm, source_file, &object, "names", "Nonlocal")?, + names: get_node_list_field(vm, source_file, object, "names", "Nonlocal")?, range, }) } @@ -1658,19 +1665,19 @@ impl Node for ast::StmtNonlocal { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "Nonlocal")?; - stmt_nonlocal_from_object_with_range(vm, source_file, _object, range) + stmt_nonlocal_from_object_with_range(vm, source_file, &_object, range) } } // constructor fn stmt_expr_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::StmtExpr { node_index: Default::default(), - value: get_required_node_field(vm, source_file, &object, "value", "Expr")?, + value: get_required_node_field(vm, source_file, object, "value", "Expr")?, range, }) } @@ -1697,7 +1704,7 @@ impl Node for ast::StmtExpr { _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, _object.clone(), "Expr")?; - stmt_expr_from_object_with_range(vm, source_file, _object, range) + stmt_expr_from_object_with_range(vm, source_file, &_object, range) } } // constructor diff --git a/crates/vm/src/stdlib/_ast/string.rs b/crates/vm/src/stdlib/_ast/string.rs index ec7d6eb5a..3c7bd270d 100644 --- a/crates/vm/src/stdlib/_ast/string.rs +++ b/crates/vm/src/stdlib/_ast/string.rs @@ -534,11 +534,11 @@ fn joined_str_part_to_ruff_fstring_element( pub(super) fn joined_str_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let values: Vec> = - get_node_list_field(vm, source_file, &object, "values", "JoinedStr")?; + get_node_list_field(vm, source_file, object, "values", "JoinedStr")?; Ok(JoinedStr { values: Vec::new().into_boxed_slice(), runtime_values: Some(values), @@ -572,7 +572,7 @@ impl Node for JoinedStr { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "JoinedStr")?; - joined_str_from_object_with_range(vm, source_file, object, range) + joined_str_from_object_with_range(vm, source_file, &object, range) } } @@ -623,17 +623,17 @@ pub(super) struct FormattedValue { pub(super) fn formatted_value_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(FormattedValue { - value: get_required_node_field(vm, source_file, &object, "value", "FormattedValue")?, + value: get_required_node_field(vm, source_file, object, "value", "FormattedValue")?, conversion: Node::ast_from_object( vm, source_file, - get_node_field(vm, &object, "conversion", "FormattedValue")?, + get_node_field(vm, object, "conversion", "FormattedValue")?, )?, - format_spec: get_node_field_opt(vm, &object, "format_spec")? + format_spec: get_node_field_opt(vm, object, "format_spec")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, range, @@ -671,7 +671,7 @@ impl Node for FormattedValue { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "FormattedValue")?; - formatted_value_from_object_with_range(vm, source_file, object, range) + formatted_value_from_object_with_range(vm, source_file, &object, range) } } @@ -1044,11 +1044,11 @@ fn template_part_to_element( pub(super) fn template_str_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { let values: Vec> = - get_node_list_field(vm, source_file, &object, "values", "TemplateStr")?; + get_node_list_field(vm, source_file, object, "values", "TemplateStr")?; Ok(TemplateStr { values: Vec::new().into_boxed_slice(), runtime_values: Some(values), @@ -1082,7 +1082,7 @@ impl Node for TemplateStr { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "TemplateStr")?; - template_str_from_object_with_range(vm, source_file, object, range) + template_str_from_object_with_range(vm, source_file, &object, range) } } @@ -1134,17 +1134,17 @@ pub(super) struct TStringInterpolation { pub(super) fn tstring_interpolation_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { - let value = get_required_node_field(vm, source_file, &object, "value", "Interpolation")?; - let str = get_node_field(vm, &object, "str", "Interpolation")?; + let value = get_required_node_field(vm, source_file, object, "value", "Interpolation")?; + let str = get_node_field(vm, object, "str", "Interpolation")?; let conversion = Node::ast_from_object( vm, source_file, - get_node_field(vm, &object, "conversion", "Interpolation")?, + get_node_field(vm, object, "conversion", "Interpolation")?, )?; - let format_spec: Option> = get_node_field_opt(vm, &object, "format_spec")? + let format_spec: Option> = get_node_field_opt(vm, object, "format_spec")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?; Ok(TStringInterpolation { @@ -1189,7 +1189,7 @@ impl Node for TStringInterpolation { object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, object.clone(), "Interpolation")?; - tstring_interpolation_from_object_with_range(vm, source_file, object, range) + tstring_interpolation_from_object_with_range(vm, source_file, &object, range) } } diff --git a/crates/vm/src/stdlib/_ast/type_parameters.rs b/crates/vm/src/stdlib/_ast/type_parameters.rs index 8f2296ea7..01a666aa4 100644 --- a/crates/vm/src/stdlib/_ast/type_parameters.rs +++ b/crates/vm/src/stdlib/_ast/type_parameters.rs @@ -102,17 +102,17 @@ impl Node for ast::TypeParam { TypeParamKind::TypeVar => Self::TypeVar(type_var_from_object_with_range( vm, source_file, - object, + &object, range, )?), TypeParamKind::ParamSpec => Self::ParamSpec(param_spec_from_object_with_range( vm, source_file, - object, + &object, range, )?), TypeParamKind::TypeVarTuple => Self::TypeVarTuple( - type_var_tuple_from_object_with_range(vm, source_file, object, range)?, + type_var_tuple_from_object_with_range(vm, source_file, &object, range)?, ), }) } @@ -122,16 +122,16 @@ impl Node for ast::TypeParam { fn type_var_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::TypeParamTypeVar { node_index: Default::default(), - name: get_required_identifier_field(vm, source_file, &object, "name", "TypeVar")?, - bound: get_node_field_opt(vm, &object, "bound")? + name: get_required_identifier_field(vm, source_file, object, "name", "TypeVar")?, + bound: get_node_field_opt(vm, object, "bound")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - default: get_node_field_opt(vm, &object, "default_value")? + default: get_node_field_opt(vm, object, "default_value")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, range, @@ -167,7 +167,7 @@ impl Node for ast::TypeParamTypeVar { object: PyObjectRef, ) -> PyResult { let range = type_param_range_from_object(vm, source_file, object.clone())?; - type_var_from_object_with_range(vm, source_file, object, range) + type_var_from_object_with_range(vm, source_file, &object, range) } } @@ -175,13 +175,13 @@ impl Node for ast::TypeParamTypeVar { fn param_spec_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::TypeParamParamSpec { node_index: Default::default(), - name: get_required_identifier_field(vm, source_file, &object, "name", "ParamSpec")?, - default: get_node_field_opt(vm, &object, "default_value")? + name: get_required_identifier_field(vm, source_file, object, "name", "ParamSpec")?, + default: get_node_field_opt(vm, object, "default_value")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, range, @@ -214,7 +214,7 @@ impl Node for ast::TypeParamParamSpec { object: PyObjectRef, ) -> PyResult { let range = type_param_range_from_object(vm, source_file, object.clone())?; - param_spec_from_object_with_range(vm, source_file, object, range) + param_spec_from_object_with_range(vm, source_file, &object, range) } } @@ -222,13 +222,13 @@ impl Node for ast::TypeParamParamSpec { fn type_var_tuple_from_object_with_range( vm: &VirtualMachine, source_file: &SourceFile, - object: PyObjectRef, + object: &PyObject, range: TextRange, ) -> PyResult { Ok(ast::TypeParamTypeVarTuple { node_index: Default::default(), - name: get_required_identifier_field(vm, source_file, &object, "name", "TypeVarTuple")?, - default: get_node_field_opt(vm, &object, "default_value")? + name: get_required_identifier_field(vm, source_file, object, "name", "TypeVarTuple")?, + default: get_node_field_opt(vm, object, "default_value")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, range, @@ -264,6 +264,6 @@ impl Node for ast::TypeParamTypeVarTuple { object: PyObjectRef, ) -> PyResult { let range = type_param_range_from_object(vm, source_file, object.clone())?; - type_var_tuple_from_object_with_range(vm, source_file, object, range) + type_var_tuple_from_object_with_range(vm, source_file, &object, range) } } diff --git a/crates/vm/src/stdlib/_collections.rs b/crates/vm/src/stdlib/_collections.rs index b76c12f51..9ec676471 100644 --- a/crates/vm/src/stdlib/_collections.rs +++ b/crates/vm/src/stdlib/_collections.rs @@ -329,8 +329,8 @@ mod _collections { .ok_or_else(|| vm.new_index_error("deque index out of range")) } - fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self._contains(&needle, vm) + fn __contains__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + self._contains(needle, vm) } fn _contains(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { @@ -950,7 +950,7 @@ mod _collections { } impl PyDefaultDict { - fn __or__(lhs: PyObjectRef, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn __or__(lhs: &PyObject, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult { let not_implemented = || Ok(vm.ctx.not_implemented.clone().into()); let (default_factory, dict) = if let Some(zelf) = lhs.downcast_ref::() { @@ -1048,9 +1048,7 @@ mod _collections { impl AsNumber for PyDefaultDict { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { - or: Some(|a, b, vm| { - PyDefaultDict::__or__(a.to_pyobject(vm), b.to_pyobject(vm), vm) - }), + or: Some(|a, b, vm| PyDefaultDict::__or__(a, b.to_pyobject(vm), vm)), ..PyNumberMethods::NOT_IMPLEMENTED }; &AS_NUMBER diff --git a/crates/vm/src/stdlib/_ctypes.rs b/crates/vm/src/stdlib/_ctypes.rs index 2cffd8c8a..d1fae5a5c 100644 --- a/crates/vm/src/stdlib/_ctypes.rs +++ b/crates/vm/src/stdlib/_ctypes.rs @@ -831,13 +831,13 @@ pub(crate) mod _ctypes { ctype: PyObjectRef, vm: &VirtualMachine, ) -> PyResult { - super::function::cast_impl(obj, src, ctype, vm) + super::function::cast_impl(&obj, src, ctype, vm) } /// Python-level cast function (PYFUNCTYPE wrapper) #[pyfunction] fn cast(obj: PyObjectRef, typ: PyObjectRef, vm: &VirtualMachine) -> PyResult { - super::function::cast_impl(obj.clone(), obj, typ, vm) + super::function::cast_impl(&obj, obj.clone(), typ, vm) } /// Return buffer interface information for a ctypes type or object. diff --git a/crates/vm/src/stdlib/_ctypes/array.rs b/crates/vm/src/stdlib/_ctypes/array.rs index 51ae363d8..fe7c96a83 100644 --- a/crates/vm/src/stdlib/_ctypes/array.rs +++ b/crates/vm/src/stdlib/_ctypes/array.rs @@ -436,7 +436,7 @@ impl Constructor for PyCArray { // Initialize elements using setitem_by_index (Array_init pattern) for (i, value) in args.args.iter().enumerate() { - Self::setitem_by_index(&instance, i as isize, value.clone(), vm)?; + Self::setitem_by_index(&instance, i as isize, value, vm)?; } Ok(instance.into()) @@ -453,7 +453,7 @@ impl Initializer for PyCArray { fn init(zelf: PyRef, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { // Re-initialize array elements when __init__ is called for (i, value) in args.args.iter().enumerate() { - Self::setitem_by_index(&zelf, i as isize, value.clone(), vm)?; + Self::setitem_by_index(&zelf, i as isize, value, vm)?; } Ok(()) } @@ -473,7 +473,7 @@ impl AsSequence for PyCArray { ass_item: atomic_func!(|seq, i, value, vm| { let zelf = PyCArray::sequence_downcast(seq); match value { - Some(v) => PyCArray::setitem_by_index(zelf, i, v, vm), + Some(v) => PyCArray::setitem_by_index(zelf, i, &v, vm), None => Err(vm.new_type_error("cannot delete array elements")), } }), @@ -492,12 +492,12 @@ impl AsMapping for PyCArray { }), subscript: atomic_func!(|mapping, needle, vm| { let zelf = PyCArray::mapping_downcast(mapping); - PyCArray::__getitem__(zelf, needle.to_owned(), vm) + PyCArray::__getitem__(zelf, needle, vm) }), ass_subscript: atomic_func!(|mapping, needle, value, vm| { let zelf = PyCArray::mapping_downcast(mapping); match value { - Some(value) => PyCArray::__setitem__(zelf, needle.to_owned(), value, vm), + Some(value) => PyCArray::__setitem__(zelf, needle, value, vm), None => PyCArray::__delitem__(zelf, needle.to_owned(), vm), } }), @@ -787,7 +787,7 @@ impl PyCArray { fn setitem_by_index( zelf: &Py, i: isize, - value: PyObjectRef, + value: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { let stg = zelf.class().stg_info_opt(); @@ -827,7 +827,7 @@ impl PyCArray { final_offset, element_size, type_code.as_deref(), - &value, + value, zelf, index, vm, @@ -838,7 +838,7 @@ impl PyCArray { final_offset, element_size, type_code.as_deref(), - &value, + value, zelf, index, vm, @@ -847,7 +847,7 @@ impl PyCArray { } // Array_subscript - fn __getitem__(zelf: &Py, item: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn __getitem__(zelf: &Py, item: &PyObject, vm: &VirtualMachine) -> PyResult { // PyIndex_Check if let Some(i) = item.downcast_ref::() { let i = i.as_bigint().to_isize().ok_or_else(|| { @@ -953,7 +953,7 @@ impl PyCArray { // Array_ass_subscript fn __setitem__( zelf: &Py, - item: PyObjectRef, + item: &PyObject, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { @@ -966,11 +966,11 @@ impl PyCArray { vm.new_index_error("cannot fit index into an index-sized integer") })?; // setitem_by_index handles negative index normalization - Self::setitem_by_index(zelf, i, value, vm) + Self::setitem_by_index(zelf, i, &value, vm) } // PySlice_Check else if let Some(slice) = item.downcast_ref::() { - Self::setitem_by_slice(zelf, slice, value, vm) + Self::setitem_by_slice(zelf, slice, &value, vm) } else { Err(vm.new_type_error("indices must be integer")) } @@ -985,7 +985,7 @@ impl PyCArray { fn setitem_by_slice( zelf: &Py, slice: &Py, - value: PyObjectRef, + value: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { let length = zelf.class().stg_info_opt().map_or(0, |i| i.length); @@ -1006,13 +1006,13 @@ impl PyCArray { return Err(vm.new_value_error("Can only assign sequence of same size")); } - let items: Vec = vm.extract_elements_with(&value, Ok)?; + let items: Vec = vm.extract_elements_with(value, Ok)?; // Use SaturatedSliceIter for correct index iteration (handles negative step) let iter = SaturatedSliceIter::from_adjust_indices(range, step, slice_len); for (idx, item) in iter.zip(items) { - Self::setitem_by_index(zelf, idx as isize, item, vm)?; + Self::setitem_by_index(zelf, idx as isize, &item, vm)?; } Ok(()) } diff --git a/crates/vm/src/stdlib/_ctypes/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index 334f2064f..c029ab203 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -530,7 +530,7 @@ fn cast_check_pointertype(ctype: &PyObject, vm: &VirtualMachine) -> bool { /// cast implementation /// _ctypes.c cast() pub(super) fn cast_impl( - obj: PyObjectRef, + obj: &PyObject, src: PyObjectRef, ctype: PyObjectRef, vm: &VirtualMachine, @@ -544,7 +544,7 @@ pub(super) fn cast_impl( } // 2. Extract pointer value - matches c_void_p_from_param_impl order - let ptr_value: usize = if vm.is_none(&obj) { + let ptr_value: usize = if vm.is_none(obj) { // None → NULL pointer 0 } else if let Ok(int_val) = obj.try_int(vm) { @@ -865,7 +865,7 @@ impl Constructor for PyCFuncPtr { fn handle_internal_func(addr: usize, args: &FuncArgs, vm: &VirtualMachine) -> Option { if addr == INTERNAL_CAST_ADDR { let result: PyResult<(PyObjectRef, PyObjectRef, PyObjectRef)> = args.clone().bind(vm); - return Some(result.and_then(|(obj, src, ctype)| cast_impl(obj, src, ctype, vm))); + return Some(result.and_then(|(obj, src, ctype)| cast_impl(&obj, src, ctype, vm))); } if addr == INTERNAL_STRING_AT_ADDR { diff --git a/crates/vm/src/stdlib/_ctypes/pointer.rs b/crates/vm/src/stdlib/_ctypes/pointer.rs index 0c7fdc5b5..f2fe5e881 100644 --- a/crates/vm/src/stdlib/_ctypes/pointer.rs +++ b/crates/vm/src/stdlib/_ctypes/pointer.rs @@ -382,7 +382,7 @@ impl PyCPointer { } // Pointer_subscript - fn __getitem__(zelf: &Py, item: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn __getitem__(zelf: &Py, item: &PyObject, vm: &VirtualMachine) -> PyResult { // PyIndex_Check if let Some(i) = item.downcast_ref::() { let i = i.as_bigint().to_isize().ok_or_else(|| { @@ -545,7 +545,7 @@ impl PyCPointer { // Pointer_ass_item fn __setitem__( zelf: &Py, - item: PyObjectRef, + item: &PyObject, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { @@ -749,12 +749,12 @@ impl AsMapping for PyCPointer { static AS_MAPPING: LazyLock = LazyLock::new(|| PyMappingMethods { subscript: atomic_func!(|mapping, needle, vm| { let zelf = PyCPointer::mapping_downcast(mapping); - PyCPointer::__getitem__(zelf, needle.to_owned(), vm) + PyCPointer::__getitem__(zelf, needle, vm) }), ass_subscript: atomic_func!(|mapping, needle, value, vm| { let zelf = PyCPointer::mapping_downcast(mapping); match value { - Some(value) => PyCPointer::__setitem__(zelf, needle.to_owned(), value, vm), + Some(value) => PyCPointer::__setitem__(zelf, needle, value, vm), None => Err(vm.new_type_error("Pointer does not support item deletion")), } }), diff --git a/crates/vm/src/stdlib/_ctypes/structure.rs b/crates/vm/src/stdlib/_ctypes/structure.rs index e9c36370c..39ab31a27 100644 --- a/crates/vm/src/stdlib/_ctypes/structure.rs +++ b/crates/vm/src/stdlib/_ctypes/structure.rs @@ -5,7 +5,7 @@ use crate::function::{FuncArgs, OptionalArg, PySetterValue}; use crate::protocol::{BufferDescriptor, PyBuffer, PyNumberMethods}; use crate::stdlib::_warnings; use crate::types::{AsBuffer, AsNumber, Constructor, Initializer, SetAttr}; -use crate::{AsObject, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine}; +use crate::{AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine}; use alloc::borrow::Cow; use core::fmt::Debug; use num_traits::ToPrimitive; @@ -85,7 +85,7 @@ impl Initializer for PyCStructType { // Process _fields_ if defined directly on this class (not inherited) if let Some(fields_attr) = new_type.get_direct_attr(vm.ctx.intern_str("_fields_")) { - Self::process_fields(&new_type, fields_attr, vm)?; + Self::process_fields(&new_type, &fields_attr, vm)?; } else { // No _fields_ defined - try to copy from base class (PyCStgInfo_clone) let (has_base_info, base_clone) = { @@ -221,7 +221,7 @@ impl PyCStructType { // Check if _fields_ is defined if let Some(fields_attr) = cls.get_direct_attr(vm.ctx.intern_str("_fields_")) { - Self::process_fields(&cls, fields_attr, vm)?; + Self::process_fields(&cls, &fields_attr, vm)?; } Ok(()) } @@ -229,7 +229,7 @@ impl PyCStructType { /// Process _fields_ and create CField descriptors fn process_fields( cls: &Py, - fields_attr: PyObjectRef, + fields_attr: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { // Check if this is a swapped byte order structure @@ -622,7 +622,7 @@ impl SetAttr for PyCStructType { return Err(vm.new_attribute_error("cannot delete _fields_")); }; // Process fields (this will also set DICTFLAG_FINAL) - Self::process_fields(pytype, fields_value.clone(), vm)?; + Self::process_fields(pytype, &fields_value, vm)?; // Set the _fields_ attribute on the type pytype .attributes diff --git a/crates/vm/src/stdlib/_ctypes/union.rs b/crates/vm/src/stdlib/_ctypes/union.rs index 982c6d711..2acf70144 100644 --- a/crates/vm/src/stdlib/_ctypes/union.rs +++ b/crates/vm/src/stdlib/_ctypes/union.rs @@ -6,7 +6,7 @@ use crate::function::{ArgBytesLike, FuncArgs, OptionalArg, PySetterValue}; use crate::protocol::{BufferDescriptor, PyBuffer}; use crate::stdlib::_warnings; use crate::types::{AsBuffer, Constructor, Initializer, SetAttr}; -use crate::{AsObject, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine}; +use crate::{AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine}; use alloc::borrow::Cow; use num_traits::ToPrimitive; @@ -140,7 +140,7 @@ impl PyCUnionType { /// For Union, all fields start at offset 0 fn process_fields( cls: &Py, - fields_attr: PyObjectRef, + fields_attr: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { // Check if already finalized @@ -469,7 +469,7 @@ impl PyCUnionType { // Check if _fields_ is defined if let Some(fields_attr) = cls.get_direct_attr(vm.ctx.intern_str("_fields_")) { - Self::process_fields(&cls, fields_attr, vm)?; + Self::process_fields(&cls, &fields_attr, vm)?; } Ok(()) } @@ -495,7 +495,7 @@ impl SetAttr for PyCUnionType { if attr_name.as_bytes() == b"_fields_" && let PySetterValue::Assign(fields_value) = value { - Self::process_fields(pytype, fields_value, vm)?; + Self::process_fields(pytype, &fields_value, vm)?; } return Ok(()); } @@ -506,7 +506,7 @@ impl SetAttr for PyCUnionType { if attr_name.as_bytes() == b"_fields_" && let PySetterValue::Assign(ref fields_value) = value { - Self::process_fields(pytype, fields_value.clone(), vm)?; + Self::process_fields(pytype, fields_value, vm)?; } // Store in type's attributes dict diff --git a/crates/vm/src/stdlib/_io.rs b/crates/vm/src/stdlib/_io.rs index c8ece805f..e90cac5ea 100644 --- a/crates/vm/src/stdlib/_io.rs +++ b/crates/vm/src/stdlib/_io.rs @@ -736,15 +736,15 @@ mod _io { } fn _readinto( - zelf: PyObjectRef, - buf_obj: PyObjectRef, + zelf: &PyObject, + buf_obj: &PyObject, method: &str, vm: &VirtualMachine, ) -> PyResult { - let b = ArgMemoryBuffer::try_from_borrowed_object(vm, &buf_obj)?; + let b = ArgMemoryBuffer::try_from_borrowed_object(vm, buf_obj)?; let l = b.len(); - let data = vm.call_method(&zelf, method, (l,))?; - if data.is(&buf_obj) { + let data = vm.call_method(zelf, method, (l,))?; + if data.is(buf_obj) { return Ok(l); } let mut buf = b.borrow_buf_mut(); @@ -762,12 +762,12 @@ mod _io { } #[pymethod] fn readinto(zelf: PyObjectRef, b: PyObjectRef, vm: &VirtualMachine) -> PyResult { - Self::_readinto(zelf, b, "read", vm) + Self::_readinto(&zelf, &b, "read", vm) } #[pymethod] fn readinto1(zelf: PyObjectRef, b: PyObjectRef, vm: &VirtualMachine) -> PyResult { - Self::_readinto(zelf, b, "read1", vm) + Self::_readinto(&zelf, &b, "read1", vm) } #[pymethod] @@ -974,7 +974,7 @@ mod _io { fn raw_seek(&mut self, pos: Offset, whence: i32, vm: &VirtualMachine) -> PyResult { let ret = vm.call_method(self.check_init(vm)?, "seek", (pos, whence))?; - let offset = get_offset(ret, vm)?; + let offset = get_offset(&ret, vm)?; if offset < 0 { return Err( vm.new_os_error(format!("Raw stream returned invalid position {offset}")) @@ -1023,7 +1023,7 @@ mod _io { fn raw_tell(&mut self, vm: &VirtualMachine) -> PyResult { let raw = self.check_init(vm)?; let ret = vm.call_method(raw, "tell", ())?; - let offset = get_offset(ret, vm)?; + let offset = get_offset(&ret, vm)?; if offset < 0 { return Err( vm.new_os_error(format!("Raw stream returned invalid position {offset}")) @@ -1570,7 +1570,7 @@ mod _io { } } - pub(super) fn get_offset(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + pub(super) fn get_offset(obj: &PyObject, vm: &VirtualMachine) -> PyResult { let int = obj.try_index(vm)?; int.as_bigint().try_into().map_err(|_| { vm.new_value_error(format!( @@ -1700,7 +1700,7 @@ mod _io { let raw = data.check_init(vm)?; ensure_unclosed(raw, "seek of closed file", vm)?; check_seekable(raw, vm)?; - let target = get_offset(target, vm)?; + let target = get_offset(&target, vm)?; data.seek(target, whence, vm) } @@ -1859,7 +1859,7 @@ mod _io { ); } let _ = proto; - reduce_ex_for_subclass(zelf, vm) + reduce_ex_for_subclass(&zelf, vm) } #[pymethod] @@ -2424,13 +2424,13 @@ mod _io { } } - fn reduce_ex_for_subclass(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn reduce_ex_for_subclass(zelf: &PyObject, vm: &VirtualMachine) -> PyResult { let cls = zelf.class(); let new = vm .get_attribute_opt(cls.to_owned().into(), "__new__")? .ok_or_else(|| vm.new_attribute_error("type has no attribute '__new__'"))?; let args = vm.ctx.new_tuple(vec![cls.to_owned().into()]); - let state = if let Some(getstate) = vm.get_attribute_opt(zelf.clone(), "__getstate__")? { + let state = if let Some(getstate) = vm.get_attribute_opt(zelf.to_owned(), "__getstate__")? { getstate.call((), vm)? } else if let Ok(dict) = zelf.get_attr("__dict__", vm) { dict @@ -2871,7 +2871,7 @@ mod _io { .map(drop) } - fn bool_from_index(value: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn bool_from_index(value: &PyObject, vm: &VirtualMachine) -> PyResult { let int = value.try_index(vm)?; let value: i32 = int.try_to_primitive(vm)?; Ok(value != 0) @@ -3096,10 +3096,10 @@ mod _io { } if let OptionalArg::Present(Some(value)) = args.line_buffering { - line_buffering = Some(Self::bool_from_index(value, vm)?); + line_buffering = Some(Self::bool_from_index(&value, vm)?); } if let OptionalArg::Present(Some(value)) = args.write_through { - write_through = Some(Self::bool_from_index(value, vm)?); + write_through = Some(Self::bool_from_index(&value, vm)?); } if (encoding_changed || newline_changed) @@ -3896,7 +3896,7 @@ mod _io { ); } let _ = proto; - reduce_ex_for_subclass(zelf, vm) + reduce_ex_for_subclass(&zelf, vm) } } @@ -5975,7 +5975,7 @@ mod fileio { } let flush_exc = res.err(); if zelf.finalizing.load() { - Self::dealloc_warn(zelf, zelf.as_object().to_owned(), vm); + Self::dealloc_warn(zelf, zelf.as_object(), vm); } let fd = zelf.fd.swap(-1); let close_err = if fd >= 0 { @@ -6014,7 +6014,7 @@ mod fileio { ) -> PyResult { let how = how.unwrap_or(0); let fd = self.get_fd(vm)?; - let offset = get_offset(offset, vm)?; + let offset = get_offset(&offset, vm)?; host_io::seek(fd, offset, how).map_err(|e| e.into_pyexception(vm)) } @@ -6029,7 +6029,7 @@ mod fileio { fn truncate(&self, len: OptionalOption, vm: &VirtualMachine) -> PyResult { let fd = self.get_fd(vm)?; let len = match len.flatten() { - Some(l) => get_offset(l, vm)?, + Some(l) => get_offset(&l, vm)?, None => host_io::tell(fd).map_err(|e| e.into_pyexception(vm))?, }; os::ftruncate(fd, len).map_err(|e| e.into_pyexception(vm))?; @@ -6050,13 +6050,13 @@ mod fileio { /// fileio_dealloc_warn in Modules/_io/fileio.c #[pymethod(name = "_dealloc_warn")] fn _dealloc_warn_method(zelf: &Py, source: PyObjectRef, vm: &VirtualMachine) { - Self::dealloc_warn(zelf, source, vm); + Self::dealloc_warn(zelf, &source, vm); } } impl FileIO { /// Issue ResourceWarning if fd is still open and closefd is true. - fn dealloc_warn(zelf: &Py, source: PyObjectRef, vm: &VirtualMachine) { + fn dealloc_warn(zelf: &Py, source: &PyObject, vm: &VirtualMachine) { if zelf.fd.load() >= 0 && zelf.closefd.load() { let repr = source .repr(vm) diff --git a/crates/vm/src/stdlib/_sre.rs b/crates/vm/src/stdlib/_sre.rs index edc8bf3ae..b89d5654a 100644 --- a/crates/vm/src/stdlib/_sre.rs +++ b/crates/vm/src/stdlib/_sre.rs @@ -519,12 +519,12 @@ mod _sre { #[pymethod] fn sub(zelf: PyRef, sub_args: SubArgs, vm: &VirtualMachine) -> PyResult { - Self::sub_impl(zelf, sub_args, false, vm) + Self::sub_impl(&zelf, sub_args, false, vm) } #[pymethod] fn subn(zelf: PyRef, sub_args: SubArgs, vm: &VirtualMachine) -> PyResult { - Self::sub_impl(zelf, sub_args, true, vm) + Self::sub_impl(&zelf, sub_args, true, vm) } #[pymethod] @@ -591,7 +591,7 @@ mod _sre { } fn sub_impl( - zelf: PyRef, + zelf: &Py, sub_args: SubArgs, subn: bool, vm: &VirtualMachine, @@ -618,14 +618,14 @@ mod _sre { }; if is_template { - FilterType::Template(Template::compile(zelf.clone(), repl, vm)?) + FilterType::Template(Template::compile(zelf.to_owned(), repl, vm)?) } else { FilterType::Literal(repl) } }; with_sre_str!(zelf, &string, vm, |s| { - let req = s.create_request(&zelf, 0, usize::MAX); + let req = s.create_request(zelf, 0, usize::MAX); let state = State::default(); let mut sub_list: Vec = Vec::new(); let mut iter = SearchIter { req, state }; @@ -641,12 +641,12 @@ mod _sre { match &filter { FilterType::Literal(literal) => sub_list.push(literal.clone()), FilterType::Callable(callable) => { - let m = Match::new(&mut iter.state, zelf.clone(), string.clone()) + let m = Match::new(&mut iter.state, zelf.to_owned(), string.clone()) .into_ref(&vm.ctx); sub_list.push(callable.invoke((m,), vm)?); } FilterType::Template(template) => { - let m = Match::new(&mut iter.state, zelf.clone(), string.clone()); + let m = Match::new(&mut iter.state, zelf.to_owned(), string.clone()); m.expand_template(template, s, &mut sub_list, vm); } }; @@ -863,7 +863,7 @@ mod _sre { vm: &VirtualMachine, ) -> PyResult<(isize, isize)> { let index = group.map_or(Ok(0), |group| { - self.get_index(group, vm) + self.get_index(&group, vm) .ok_or_else(|| vm.new_index_error("no such group")) })?; Ok(self.regs[index]) @@ -895,7 +895,7 @@ mod _sre { let mut v: Vec = args .into_iter() .map(|x| { - self.get_index(x, vm) + self.get_index(&x, vm) .ok_or_else(|| vm.new_index_error("no such group")) .map(|index| { self.get_slice(index, str_drive, vm) @@ -918,7 +918,7 @@ mod _sre { ) -> PyResult> { with_sre_str!(self.pattern, &self.string, vm, |str_drive| { let i = self - .get_index(group, vm) + .get_index(&group, vm) .ok_or_else(|| vm.new_index_error("no such group"))?; Ok(self.get_slice(i, str_drive, vm)) }) @@ -956,7 +956,7 @@ mod _sre { for (key, index) in self.pattern.groupindex.clone() { let value = self - .get_index(index, vm) + .get_index(&index, vm) .and_then(|x| self.get_slice(x, str_drive, vm)) .map_or_else(|| default.clone(), |x| x.to_pyobject(vm)); dict.set_item(&*key, value, vm)?; @@ -965,13 +965,13 @@ mod _sre { }) } - fn get_index(&self, group: PyObjectRef, vm: &VirtualMachine) -> Option { + fn get_index(&self, group: &PyObject, vm: &VirtualMachine) -> Option { let i = if let Ok(i) = group.try_index(vm) { i } else { self.pattern .groupindex - .get_item_opt(&*group, vm) + .get_item_opt(group, vm) .ok()?? .downcast::() .ok()? diff --git a/crates/vm/src/stdlib/_typing.rs b/crates/vm/src/stdlib/_typing.rs index 33dfbc57b..7e27c3767 100644 --- a/crates/vm/src/stdlib/_typing.rs +++ b/crates/vm/src/stdlib/_typing.rs @@ -289,7 +289,7 @@ pub(crate) mod decl { vm.ctx.none() } - fn __getitem__(zelf: PyRef, args: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn __getitem__(zelf: &Py, args: PyObjectRef, vm: &VirtualMachine) -> PyResult { if zelf.type_params.is_empty() { return Err(vm.new_type_error("Only generic type aliases are subscriptable")); } @@ -446,7 +446,7 @@ pub(crate) mod decl { static AS_MAPPING: LazyLock = LazyLock::new(|| PyMappingMethods { subscript: atomic_func!(|mapping, needle, vm| { let zelf = TypeAliasType::mapping_downcast(mapping); - TypeAliasType::__getitem__(zelf.to_owned(), needle.to_owned(), vm) + TypeAliasType::__getitem__(zelf, needle.to_owned(), vm) }), ..PyMappingMethods::NOT_IMPLEMENTED }); diff --git a/crates/vm/src/stdlib/itertools.rs b/crates/vm/src/stdlib/itertools.rs index c52fc6d1d..24e69b770 100644 --- a/crates/vm/src/stdlib/itertools.rs +++ b/crates/vm/src/stdlib/itertools.rs @@ -3,7 +3,7 @@ pub(crate) use decl::module_def; #[pymodule(name = "itertools")] mod decl { use crate::{ - AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, PyWeakRef, VirtualMachine, + AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, PyWeakRef, VirtualMachine, builtins::{ PyGenericAlias, PyInt, PyIntRef, PyList, PyTuple, PyTupleRef, PyType, PyTypeRef, int, }, @@ -730,13 +730,13 @@ mod decl { // Restrict obj to ints with value 0 <= val <= sys.maxsize // On failure (out of range, non-int object) a ValueError is raised. fn pyobject_to_opt_usize( - obj: PyObjectRef, + obj: &PyObject, name: &'static str, vm: &VirtualMachine, ) -> PyResult { let is_int = obj.fast_isinstance(vm.ctx.types.int_type); if is_int { - let value = int::get_value(&obj).to_usize(); + let value = int::get_value(obj).to_usize(); if let Some(value) = value { // Only succeeds for values for which 0 <= value <= sys.maxsize if value <= sys::MAXSIZE as usize { @@ -776,14 +776,14 @@ mod decl { ) = args.bind_for(vm, Self::NAME)?; let step = if !vm.is_none(&step) { - pyobject_to_opt_usize(step, "Step", vm)? + pyobject_to_opt_usize(&step, "Step", vm)? } else { 1usize }; (iter, start, stop, step) }; let start = if !vm.is_none(&start) { - pyobject_to_opt_usize(start, "Start", vm)? + pyobject_to_opt_usize(&start, "Start", vm)? } else { 0usize }; @@ -793,7 +793,7 @@ mod decl { }; let stop = if !vm.is_none(&stop) { - Some(pyobject_to_opt_usize(stop, "Stop", vm)?) + Some(pyobject_to_opt_usize(&stop, "Stop", vm)?) } else { None }; diff --git a/crates/vm/src/stdlib/posix.rs b/crates/vm/src/stdlib/posix.rs index fcfa23f1f..26950e37d 100644 --- a/crates/vm/src/stdlib/posix.rs +++ b/crates/vm/src/stdlib/posix.rs @@ -17,7 +17,7 @@ pub use rustpython_host_env::posix::set_inheritable; ))] pub mod module { use crate::{ - AsObject, Py, PyObjectRef, PyResult, VirtualMachine, + AsObject, Py, PyObject, PyObjectRef, PyResult, VirtualMachine, builtins::{PyBytesRef, PyDictRef, PyInt, PyListRef, PyTuple, PyTupleRef, PyUtf8Str}, convert::{IntoPyException, ToPyException, ToPyObject, TryFromObject}, exceptions::OSErrorBuilder, @@ -1370,7 +1370,7 @@ pub mod module { rustpython_host_env::posix::tcsetpgrp(fd, pgid).map_err(|err| err.into_pyexception(vm)) } - fn try_from_id(vm: &VirtualMachine, obj: PyObjectRef, typ_name: &str) -> PyResult { + fn try_from_id(vm: &VirtualMachine, obj: &PyObject, typ_name: &str) -> PyResult { use core::cmp::Ordering; let i = obj .try_to_ref::(vm) @@ -1404,13 +1404,13 @@ pub mod module { impl TryFromObject for RawUid { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - try_from_id(vm, obj, "uid").map(Self) + try_from_id(vm, &obj, "uid").map(Self) } } impl TryFromObject for RawGid { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - try_from_id(vm, obj, "gid").map(Self) + try_from_id(vm, &obj, "gid").map(Self) } } diff --git a/crates/vm/src/stdlib/sys.rs b/crates/vm/src/stdlib/sys.rs index d8cda5a81..dcee2aaa0 100644 --- a/crates/vm/src/stdlib/sys.rs +++ b/crates/vm/src/stdlib/sys.rs @@ -34,7 +34,7 @@ mod sys_jit { #[pymodule] pub mod sys { use crate::{ - AsObject, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult, + AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult, builtins::{ PyBaseExceptionRef, PyDictRef, PyFrozenSet, PyNamespace, PyStr, PyStrRef, PyTuple, PyTupleRef, PyTypeRef, PyUtf8StrRef, @@ -1743,7 +1743,7 @@ pub mod sys { impl PyUnraisableHookArgs {} pub(crate) fn run_audit_hooks( - event: PyStrRef, + event: &Py, args: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { @@ -1754,7 +1754,7 @@ pub mod sys { } for hook in hooks { - call_audit_hook(&hook, event.clone().into(), args, vm)?; + call_audit_hook(&hook, event.to_owned().into(), args, vm)?; } Ok(()) @@ -1809,7 +1809,7 @@ pub mod sys { } let args_tup: PyObjectRef = vm.ctx.new_tuple(args.into_vec()).into(); - run_audit_hooks(event, &args_tup, vm) + run_audit_hooks(&event, &args_tup, vm) } #[pyfunction] diff --git a/crates/vm/src/stdlib/sys/monitoring.rs b/crates/vm/src/stdlib/sys/monitoring.rs index b50c7083c..28374ea7d 100644 --- a/crates/vm/src/stdlib/sys/monitoring.rs +++ b/crates/vm/src/stdlib/sys/monitoring.rs @@ -759,7 +759,7 @@ fn set_events(tool_id: i32, event_set: i32, vm: &VirtualMachine) -> PyResult<()> Ok(()) } -fn get_local_events(tool_id: i32, code: PyObjectRef, vm: &VirtualMachine) -> PyResult { +fn get_local_events(tool_id: i32, code: &PyObject, vm: &VirtualMachine) -> PyResult { if code.downcast_ref::().is_none() { return Err(vm.new_type_error("code must be a code object")); } @@ -775,7 +775,7 @@ fn get_local_events(tool_id: i32, code: PyObjectRef, vm: &VirtualMachine) -> PyR fn set_local_events( tool_id: i32, - code: PyObjectRef, + code: &PyObject, event_set: i32, vm: &VirtualMachine, ) -> PyResult<()> { @@ -1309,7 +1309,7 @@ pub(super) mod sys_monitoring { #[pyfunction] fn get_local_events(tool_id: i32, code: PyObjectRef, vm: &VirtualMachine) -> PyResult { - super::get_local_events(tool_id, code, vm) + super::get_local_events(tool_id, &code, vm) } #[pyfunction] @@ -1319,7 +1319,7 @@ pub(super) mod sys_monitoring { event_set: i32, vm: &VirtualMachine, ) -> PyResult<()> { - super::set_local_events(tool_id, code, event_set, vm) + super::set_local_events(tool_id, &code, event_set, vm) } #[pyfunction] diff --git a/crates/vm/src/vm/compile.rs b/crates/vm/src/vm/compile.rs index 69cfc3e39..f12e8b3ef 100644 --- a/crates/vm/src/vm/compile.rs +++ b/crates/vm/src/vm/compile.rs @@ -441,7 +441,7 @@ impl VirtualMachine { ) .map_err(|e| (e, Some(source), allow_incomplete).to_pyexception(self))?; if start == PY_SINGLE_INPUT { - return _ast::wrap_interactive(self, parsed); + return _ast::wrap_interactive(self, &parsed); } return Ok(parsed); } diff --git a/crates/vm/src/vm/mod.rs b/crates/vm/src/vm/mod.rs index 5750c0626..a46141db0 100644 --- a/crates/vm/src/vm/mod.rs +++ b/crates/vm/src/vm/mod.rs @@ -1523,7 +1523,7 @@ impl VirtualMachine { #[cfg(feature = "host_env")] if self.state.config.settings.allow_external_library && cfg!(feature = "rustpython-compiler") - && let Err(e) = import::init_importlib_package(self, importlib) + && let Err(e) = import::init_importlib_package(self, &importlib) { eprintln!( "importlib initialization failed. This is critical for many complicated packages." diff --git a/crates/vm/src/warn.rs b/crates/vm/src/warn.rs index 35bafcfc2..f7336bbd8 100644 --- a/crates/vm/src/warn.rs +++ b/crates/vm/src/warn.rs @@ -2,7 +2,7 @@ use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyResult, VirtualMachine, builtins::{ PyBaseExceptionRef, PyDictRef, PyListRef, PyStr, PyStrInterned, PyStrRef, PyTuple, - PyTupleRef, PyTypeRef, + PyTupleRef, PyType, PyTypeRef, }, convert::TryFromObject, }; @@ -181,7 +181,7 @@ fn get_once_registry(vm: &VirtualMachine) -> PyResult { fn already_warned( registry: &PyObject, - key: PyObjectRef, + key: &PyObject, should_set: bool, vm: &VirtualMachine, ) -> PyResult { @@ -198,7 +198,7 @@ fn already_warned( }); if version_matches { - if let Ok(val) = registry.get_item(key.as_ref(), vm) + if let Ok(val) = registry.get_item(key, vm) && val.is_true(vm)? { return Ok(true); @@ -213,7 +213,7 @@ fn already_warned( } if should_set { - registry.set_item(key.as_ref(), vm.ctx.true_value.clone().into(), vm)?; + registry.set_item(key, vm.ctx.true_value.clone().into(), vm)?; } Ok(false) } @@ -240,7 +240,7 @@ fn update_registry( } else { PyTuple::new_ref(vec![text.to_owned(), category.to_owned()], &vm.ctx).into() }; - already_warned(registry, altkey, true, vm) + already_warned(registry, &altkey, true, vm) } fn normalize_module(filename: &Py, vm: &VirtualMachine) -> PyObjectRef { @@ -257,10 +257,10 @@ fn normalize_module(filename: &Py, vm: &VirtualMachine) -> PyObjectRef { // TODO: split into filter_search() + get_filter() and support // context-aware filters (get_warnings_context_filters). fn get_filter( - category: PyObjectRef, - text: PyObjectRef, + category: &PyObject, + text: &PyObject, lineno: usize, - module: PyObjectRef, + module: &PyObject, vm: &VirtualMachine, ) -> PyResult { let filters = get_warnings_filters(vm); @@ -281,9 +281,9 @@ fn get_filter( /* action, msg, cat, mod, ln = item */ let action = &tmp_item[0]; - let good_msg = check_matched(&tmp_item[1], &text, vm)?; + let good_msg = check_matched(&tmp_item[1], text, vm)?; let is_subclass = category.is_subclass(&tmp_item[2], vm)?; - let good_mod = check_matched(&tmp_item[3], &module, vm)?; + let good_mod = check_matched(&tmp_item[3], module, vm)?; let ln: usize = tmp_item[4].try_int(vm).map_or(0, |v| v.as_u32_mask() as _); if good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln) { @@ -410,18 +410,12 @@ pub fn warn_explicit( .into(); // Check if already warned - if !vm.is_none(®istry) && already_warned(®istry, key.clone(), false, vm)? { + if !vm.is_none(®istry) && already_warned(®istry, &key, false, vm)? { return Ok(()); } // Get filter action - let action = get_filter( - category.as_object().to_owned(), - text.clone().into(), - lineno, - module, - vm, - )?; + let action = get_filter(category.as_object(), text.as_object(), lineno, &module, vm)?; let action_str = PyStrRef::try_from_object(vm, action) .map_err(|_| vm.new_type_error("action must be a string"))?; @@ -499,7 +493,7 @@ fn call_show_warning( ) -> PyResult<()> { let Some(show_fn) = get_warnings_attr(vm, identifier!(&vm.ctx, _showwarnmsg), source.is_some()) else { - show_warning(filename, lineno, text, category, source_line, vm); + show_warning(&filename, lineno, &text, &category, source_line, vm); return Ok(()); }; @@ -530,10 +524,10 @@ fn call_show_warning( } fn show_warning( - filename: PyStrRef, + filename: &Py, lineno: usize, - text: PyStrRef, - category: PyTypeRef, + text: &Py, + category: &Py, _source_line: Option, vm: &VirtualMachine, ) { diff --git a/src/lib.rs b/src/lib.rs index 0e3d0b588..918e33d79 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -287,7 +287,7 @@ fn get_importer(path: &str, vm: &VirtualMachine) -> PyResult } } Ok(if let Some(imp) = importer { - let imp = path_importer_cache.get_or_insert(vm, path_obj.into(), || imp.clone())?; + let imp = path_importer_cache.get_or_insert(vm, path_obj.as_object(), || imp.clone())?; Some(imp) } else { None