Borrow tp_descr_get/tp_init arguments and by-value public helpers (#8803)

* Borrow tp_descr_get/tp_init arguments and by-value public helpers

- DescrGetFunc and GetDescriptor::descr_get take
  (&PyObject, Option<&PyObject>, Option<&PyObject>); impls call
  .to_owned() where they store or return an argument.
- InitFunc takes &PyObject and Initializer::init takes &Py<Self>.
- VirtualMachine::get_attribute_opt, print_exception,
  call_get_descriptor(_specific) and other helpers flagged by
  clippy::needless_pass_by_value take &PyObject / &Py<T>; callers in
  crates/, examples/ and tests/ drop the clones made for the call.

Assisted-by: Claude Code:claude-opus-5-5
Assisted-by: Grok CLI:grok-4.7

* Pass the borrowed zelf to internal_close in WindowsConsoleIO init

Assisted-by: Claude Code:claude-opus-5-5

* Fix borrowed signatures missed by the rebase

OrderedDict.init, classmethod_descriptor.descr_get, and the warnings
get_attribute_opt callers still used owned handles.

Assisted-by: Grok CLI:grok-4.7
This commit is contained in:
Jeong, YunWon authored and GitHub committed 2026-09-24 14:25:07 +09:00
1 parent afad92bf1b
commit 0940849029
85 files changed
+631 -623

No files matched your search

+1 -1
View File
@@ -43,7 +43,7 @@ pub unsafe extern "C" fn PyCodec_Register(search_function: *mut PyObject) -> c_i
#[unsafe(no_mangle)]
pub unsafe extern "C" fn PyCodec_Unregister(search_function: *mut PyObject) -> c_int {
with_vm(|vm| {
let search_function = unsafe { &*search_function }.to_owned();
let search_function = unsafe { &*search_function };
vm.state.codec_registry.unregister(search_function);
})
}
+1 -1
View File
@@ -294,7 +294,7 @@ pub unsafe extern "C" fn PyDict_MergeFromSeq2(
) -> c_int {
with_vm(|vm| {
let dict = unsafe { &*dict }.try_downcast_ref::<PyDict>(vm)?;
let seq2 = unsafe { &*seq2 }.to_owned();
let seq2 = unsafe { &*seq2 };
dict.merge_from_seq2(seq2, override_ != 0, vm)
})
}
+4 -4
View File
@@ -109,7 +109,7 @@ pub unsafe extern "C" fn PyObject_GetOptionalAttr(
}
let obj = unsafe { &*obj };
let name = unsafe { &*name }.try_downcast_ref::<PyStr>(vm)?;
if let Some(attr) = vm.get_attribute_opt(obj.to_owned(), name)? {
if let Some(attr) = vm.get_attribute_opt(obj, name)? {
unsafe {
*result = attr.into_raw().as_ptr();
}
@@ -132,7 +132,7 @@ pub unsafe extern "C" fn PyObject_GetOptionalAttrString(
}
let obj = unsafe { &*obj };
let name = unsafe { attr_name.try_as_str(vm) }?;
if let Some(attr) = vm.get_attribute_opt(obj.to_owned(), name)? {
if let Some(attr) = vm.get_attribute_opt(obj, name)? {
unsafe {
*result = attr.into_raw().as_ptr();
}
@@ -217,7 +217,7 @@ pub unsafe extern "C" fn PyObject_HasAttrWithError(
with_vm(|vm| {
let obj = unsafe { &*obj };
let name = unsafe { &*attr_name }.try_downcast_ref::<PyStr>(vm)?;
Ok(vm.get_attribute_opt(obj.to_owned(), name)?.is_some())
Ok(vm.get_attribute_opt(obj, name)?.is_some())
})
}
@@ -272,7 +272,7 @@ pub unsafe extern "C" fn PyObject_HasAttrStringWithError(
with_vm(|vm| {
let obj = unsafe { &*obj };
let name = unsafe { attr_name.try_as_str(vm) }?;
Ok(vm.get_attribute_opt(obj.to_owned(), name)?.is_some())
Ok(vm.get_attribute_opt(obj, name)?.is_some())
})
}
+2 -3
View File
@@ -160,7 +160,7 @@ pub extern "C" fn PyErr_PrintEx(_set_sys_last_vars: c_int) {
.take_raised_exception()
.expect("No exception set in PyErr_PrintEx");
vm.print_exception(exception);
vm.print_exception(&exception);
})
}
@@ -169,8 +169,7 @@ pub unsafe extern "C" fn PyErr_DisplayException(exc: *mut PyObject) {
with_vm(|vm| {
let exception = unsafe { &*exc }
.downcast_ref::<PyBaseException>()
.expect("PyErr_DisplayException exc must be an exception instance")
.to_owned();
.expect("PyErr_DisplayException exc must be an exception instance");
vm.print_exception(exception);
})
+30 -44
View File
@@ -36,7 +36,7 @@ pub(crate) mod _asyncio {
// Initialize module-level state
let weakref_module = vm.import("weakref", 0)?;
let weak_set_class = vm
.get_attribute_opt(weakref_module, vm.ctx.intern_str("WeakSet"))?
.get_attribute_opt(&weakref_module, vm.ctx.intern_str("WeakSet"))?
.ok_or_else(|| vm.new_attribute_error("WeakSet not found"))?;
let scheduled_tasks = weak_set_class.call((), vm)?;
let eager_tasks = PySet::default().into_ref(&vm.ctx);
@@ -52,7 +52,7 @@ pub(crate) mod _asyncio {
#[cfg(unix)]
{
let on_fork = vm
.get_attribute_opt(module.to_owned().into(), vm.ctx.intern_str("_on_fork"))?
.get_attribute_opt(module.as_object(), vm.ctx.intern_str("_on_fork"))?
.expect("_on_fork not found in _asyncio module");
vm.state.after_forkers_child.lock().push(on_fork);
}
@@ -148,14 +148,14 @@ pub(crate) mod _asyncio {
impl Initializer for PyFuture {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// Future does not accept positional arguments
if !args.args.is_empty() {
return Err(vm.new_type_error("Future() takes no positional arguments"));
}
// Extract only 'loop' keyword argument
let loop_ = args.kwargs.get("loop").cloned();
Self::py_init(&zelf, loop_, vm)
Self::py_init(zelf, loop_, vm)
}
}
@@ -198,14 +198,14 @@ pub(crate) mod _asyncio {
// Check if loop has get_debug method and call it
if let Ok(Some(get_debug)) =
vm.get_attribute_opt(loop_obj, vm.ctx.intern_str("get_debug"))
vm.get_attribute_opt(&loop_obj, vm.ctx.intern_str("get_debug"))
&& let Ok(debug) = get_debug.call((), vm)
&& debug.try_to_bool(vm).unwrap_or(false)
{
// Get source traceback
if let Ok(tb_module) = vm.import("traceback", 0)
&& let Ok(Some(extract_stack)) =
vm.get_attribute_opt(tb_module, vm.ctx.intern_str("extract_stack"))
vm.get_attribute_opt(&tb_module, vm.ctx.intern_str("extract_stack"))
&& let Ok(tb) = extract_stack.call((), vm)
{
*zelf.fut_source_tb.write() = Some(tb);
@@ -878,7 +878,7 @@ pub(crate) mod _asyncio {
}
};
let func = match vm.get_attribute_opt(module, vm.ctx.intern_str("_future_repr_info")) {
let func = match vm.get_attribute_opt(&module, vm.ctx.intern_str("_future_repr_info")) {
Ok(Some(f)) => f,
_ => return Ok(get_future_repr_info_fallback(future, vm)),
};
@@ -908,9 +908,7 @@ pub(crate) mod _asyncio {
fn get_future_repr_info_fallback(future: &PyObject, vm: &VirtualMachine) -> Wtf8Buf {
// Fallback: build repr from properties directly
if let Ok(Some(state)) =
vm.get_attribute_opt(future.to_owned(), vm.ctx.intern_str("_state"))
{
if let Ok(Some(state)) = vm.get_attribute_opt(future, vm.ctx.intern_str("_state")) {
state
.str(vm)
.map_or_else(|_| Wtf8Buf::from("unknown"), |s| s.as_wtf8().to_lowercase())
@@ -926,7 +924,7 @@ pub(crate) mod _asyncio {
.and_then(|asyncio| asyncio.get_attr(vm.ctx.intern_str("base_tasks"), vm))
{
Ok(base_tasks) => {
match vm.get_attribute_opt(base_tasks, vm.ctx.intern_str("_task_repr_info")) {
match vm.get_attribute_opt(&base_tasks, vm.ctx.intern_str("_task_repr_info")) {
Ok(Some(func)) => {
let info: PyObjectRef = func.call((task.to_owned(),), vm)?;
let list: PyListRef = info.downcast().map_err(|_| {
@@ -973,13 +971,10 @@ pub(crate) mod _asyncio {
fut.fut_blocking.load(Ordering::Relaxed)
} else {
// For non-native futures, check the attribute
vm.get_attribute_opt(
future.clone(),
vm.ctx.intern_str("_asyncio_future_blocking"),
)?
.map(|v| v.try_to_bool(vm))
.transpose()?
.unwrap_or(false)
vm.get_attribute_opt(&future, vm.ctx.intern_str("_asyncio_future_blocking"))?
.map(|v| v.try_to_bool(vm))
.transpose()?
.unwrap_or(false)
};
// Check if future is done
@@ -1172,8 +1167,8 @@ pub(crate) mod _asyncio {
impl Initializer for PyTask {
type Args = TaskInitArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
Self::py_init(&zelf, args, vm)
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
Self::py_init(zelf, args, vm)
}
}
@@ -1201,14 +1196,14 @@ pub(crate) mod _asyncio {
// Check if loop has get_debug method and capture source traceback if enabled
if let Ok(Some(get_debug)) =
vm.get_attribute_opt(loop_obj.clone(), vm.ctx.intern_str("get_debug"))
vm.get_attribute_opt(&loop_obj, vm.ctx.intern_str("get_debug"))
&& let Ok(debug) = get_debug.call((), vm)
&& debug.try_to_bool(vm).unwrap_or(false)
{
// Get source traceback
if let Ok(tb_module) = vm.import("traceback", 0)
&& let Ok(Some(extract_stack)) =
vm.get_attribute_opt(tb_module, vm.ctx.intern_str("extract_stack"))
vm.get_attribute_opt(&tb_module, vm.ctx.intern_str("extract_stack"))
&& let Ok(tb) = extract_stack.call((), vm)
{
*zelf.base.fut_source_tb.write() = Some(tb);
@@ -2171,10 +2166,7 @@ pub(crate) mod _asyncio {
}
let blocking = vm
.get_attribute_opt(
result.to_owned(),
vm.ctx.intern_str("_asyncio_future_blocking"),
)?
.get_attribute_opt(result, vm.ctx.intern_str("_asyncio_future_blocking"))?
.and_then(|v| v.try_to_bool(vm).ok())
.unwrap_or(false);
@@ -2411,20 +2403,17 @@ pub(crate) mod _asyncio {
// Slow path: (re)resolve everything and populate the cache.
let scheduled_tasks = vm
.get_attribute_opt(
asyncio_module.clone(),
vm.ctx.intern_str("_scheduled_tasks"),
)?
.get_attribute_opt(&asyncio_module, vm.ctx.intern_str("_scheduled_tasks"))?
.ok_or_else(|| vm.new_attribute_error("_scheduled_tasks not found"))?;
let eager_tasks: PyRef<PySet> = vm
.get_attribute_opt(asyncio_module.clone(), vm.ctx.intern_str("_eager_tasks"))?
.get_attribute_opt(&asyncio_module, vm.ctx.intern_str("_eager_tasks"))?
.ok_or_else(|| vm.new_attribute_error("_eager_tasks not found"))?
.downcast()
.map_err(|_| vm.new_type_error("_eager_tasks is not a set"))?;
// Lenient by design: a missing or non-dict `_current_tasks` just
// disables the cross-thread lookup instead of raising.
let current_tasks: Option<PyRef<PyDict>> = vm
.get_attribute_opt(asyncio_module.clone(), vm.ctx.intern_str("_current_tasks"))?
.get_attribute_opt(&asyncio_module, vm.ctx.intern_str("_current_tasks"))?
.and_then(|obj| obj.downcast::<PyDict>().ok());
let cache = AsyncioCache {
@@ -2453,10 +2442,7 @@ pub(crate) mod _asyncio {
}
let copy_context = vm
.get_attribute_opt(
contextvars_module.clone(),
vm.ctx.intern_str("copy_context"),
)?
.get_attribute_opt(&contextvars_module, vm.ctx.intern_str("copy_context"))?
.ok_or_else(|| vm.new_attribute_error("copy_context not found"))?;
let cache = ContextVarsCache {
@@ -2514,11 +2500,11 @@ pub(crate) mod _asyncio {
let asyncio_events = vm.import("asyncio.events", 0)?;
let get_event_loop_policy = vm
.get_attribute_opt(asyncio_events, vm.ctx.intern_str("get_event_loop_policy"))?
.get_attribute_opt(&asyncio_events, vm.ctx.intern_str("get_event_loop_policy"))?
.ok_or_else(|| vm.new_attribute_error("get_event_loop_policy"))?;
let policy = get_event_loop_policy.call((), vm)?;
let get_event_loop = vm
.get_attribute_opt(policy, vm.ctx.intern_str("get_event_loop"))?
.get_attribute_opt(&policy, vm.ctx.intern_str("get_event_loop"))?
.ok_or_else(|| vm.new_attribute_error("get_event_loop"))?;
get_event_loop.call((), vm)
}
@@ -2584,7 +2570,7 @@ pub(crate) mod _asyncio {
let task_loop = if let Ok(l) = vm.call_method(&task, "get_loop", ()) {
Some(l)
} else if let Ok(Some(l)) =
vm.get_attribute_opt(task.clone(), vm.ctx.intern_str("_loop"))
vm.get_attribute_opt(&task, vm.ctx.intern_str("_loop"))
{
Some(l)
} else {
@@ -2792,7 +2778,7 @@ pub(crate) mod _asyncio {
#[pygetset]
fn __qualname__(&self, vm: &VirtualMachine) -> PyResult<Option<PyObjectRef>> {
match self.task.read().as_ref() {
Some(t) => vm.get_attribute_opt(t.clone(), vm.ctx.intern_str("__qualname__")),
Some(t) => vm.get_attribute_opt(t, vm.ctx.intern_str("__qualname__")),
None => Ok(None),
}
}
@@ -2838,7 +2824,7 @@ pub(crate) mod _asyncio {
#[pygetset]
fn __qualname__(&self, vm: &VirtualMachine) -> PyResult<Option<PyObjectRef>> {
match self.task.read().as_ref() {
Some(t) => vm.get_attribute_opt(t.clone(), vm.ctx.intern_str("__qualname__")),
Some(t) => vm.get_attribute_opt(t, vm.ctx.intern_str("__qualname__")),
None => Ok(None),
}
}
@@ -2872,7 +2858,7 @@ pub(crate) mod _asyncio {
let asyncio_coroutines = vm.import("asyncio.coroutines", 0)?;
if let Some(iscoroutine) =
vm.get_attribute_opt(asyncio_coroutines, vm.ctx.intern_str("iscoroutine"))?
vm.get_attribute_opt(&asyncio_coroutines, vm.ctx.intern_str("iscoroutine"))?
{
let result = iscoroutine.call((obj,), vm)?;
result.try_to_bool(vm)
@@ -2884,7 +2870,7 @@ pub(crate) mod _asyncio {
fn get_invalid_state_error_type(vm: &VirtualMachine) -> PyResult<PyTypeRef> {
let module = vm.import("asyncio.exceptions", 0)?;
let exc_type = vm
.get_attribute_opt(module, vm.ctx.intern_str("InvalidStateError"))?
.get_attribute_opt(&module, vm.ctx.intern_str("InvalidStateError"))?
.ok_or_else(|| vm.new_attribute_error("InvalidStateError not found"))?;
exc_type
.downcast()
@@ -2911,7 +2897,7 @@ pub(crate) mod _asyncio {
fn get_cancelled_error_type(vm: &VirtualMachine) -> PyResult<PyTypeRef> {
let module = vm.import("asyncio.exceptions", 0)?;
let exc_type = vm
.get_attribute_opt(module, vm.ctx.intern_str("CancelledError"))?
.get_attribute_opt(&module, vm.ctx.intern_str("CancelledError"))?
.ok_or_else(|| vm.new_attribute_error("CancelledError not found"))?;
exc_type
.downcast()
+3 -3
View File
@@ -972,7 +972,7 @@ mod _sqlite3 {
impl Initializer for Connection {
type Args = ConnectArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let was_initialized = Radium::swap(&zelf.initialized, false, Ordering::AcqRel);
// Reset factories to their defaults, matching CPython's behavior.
@@ -2216,7 +2216,7 @@ mod _sqlite3 {
impl Initializer for Cursor {
type Args = PyRef<Connection>;
fn init(zelf: PyRef<Self>, _connection: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, _connection: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
let mut guard = zelf.inner.lock();
if guard.is_some() {
// Already initialized (e.g., from a call to super().__init__)
@@ -3526,7 +3526,7 @@ mod _sqlite3 {
unsafe { sqlite3_result_error(self.ctx, msg.as_ptr().cast(), -1) }
}
if enable_traceback().load(Ordering::Relaxed) {
vm.print_exception(exc);
vm.print_exception(&exc);
}
}
@@ -726,7 +726,7 @@ mod _multibytecodec {
impl Initializer for MultibyteIncrementalEncoder {
type Args = FuncArgs;
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
Ok(())
}
}
@@ -857,7 +857,7 @@ mod _multibytecodec {
impl Initializer for MultibyteIncrementalDecoder {
type Args = FuncArgs;
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
Ok(())
}
}
@@ -1000,7 +1000,7 @@ mod _multibytecodec {
impl Initializer for MultibyteStreamReader {
type Args = FuncArgs;
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
Ok(())
}
}
@@ -1164,7 +1164,7 @@ mod _multibytecodec {
impl Initializer for MultibyteStreamWriter {
type Args = FuncArgs;
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
Ok(())
}
}
+1 -1
View File
@@ -462,7 +462,7 @@ mod _csv {
_rest: FuncArgs,
vm: &VirtualMachine,
) -> PyResult<Writer> {
let write = match vm.get_attribute_opt(file.clone(), "write")? {
let write = match vm.get_attribute_opt(&file, "write")? {
Some(write_meth) => write_meth,
None if file.is_callable() => file,
None => {
+4 -4
View File
@@ -432,7 +432,7 @@ pub(crate) mod _elementtree {
impl Initializer for PyElement {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let (tag, attrib) = parse_attrib_args(args, "Element", 0, vm)?;
let attrib = attrib.filter(|d| !d.is_empty());
let _recycle = {
@@ -1367,7 +1367,7 @@ pub(crate) mod _elementtree {
impl Initializer for PyTreeBuilder {
type Args = TreeBuilderArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let module = module_state(vm)?;
let element_factory = args.element_factory.filter(|f| !vm.is_none(f));
let comment_factory = match args.comment_factory {
@@ -1917,13 +1917,13 @@ pub(crate) mod _elementtree {
name: &'static str,
vm: &VirtualMachine,
) -> PyResult<Option<PyObjectRef>> {
vm.get_attribute_opt(target.to_owned(), name)
vm.get_attribute_opt(target, name)
}
impl Initializer for PyXMLParser {
type Args = XMLParserArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let encoding = match args.encoding {
Some(e) if !vm.is_none(&e) => {
if !e.downcastable::<PyStr>() {
+5 -5
View File
@@ -656,7 +656,7 @@ mod mmap {
ass_subscript: atomic_func!(|mapping, needle, value, vm| {
let zelf = PyMmap::mapping_downcast(mapping);
if let Some(value) = value {
PyMmap::setitem_inner(zelf, needle, value, vm)
PyMmap::setitem_inner(zelf, needle, &value, vm)
} else {
Err(vm
.new_type_error("mmap object doesn't support item deletion".to_owned()))
@@ -1244,7 +1244,7 @@ mod mmap {
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
Self::setitem_inner(zelf, needle, value, vm)
Self::setitem_inner(zelf, needle, &value, vm)
}
#[pymethod]
@@ -1354,12 +1354,12 @@ mod mmap {
fn setitem_inner(
zelf: &Py<Self>,
needle: &PyObject,
value: PyObjectRef,
value: &PyObject,
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),
}
}
+21 -25
View File
@@ -499,7 +499,7 @@ mod _pickle {
impl Initializer for PyUnpickler {
type Args = UnpicklerNewArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let Some(mut state) = zelf.read_state.try_lock() else {
return Err(vm.new_runtime_error("Unpickler.__init__() called recursively"));
};
@@ -525,10 +525,10 @@ mod _pickle {
};
let file = args.file;
let peek = vm.get_attribute_opt(file.clone(), "peek")?;
let _readinto = vm.get_attribute_opt(file.clone(), "readinto")?;
let read = vm.get_attribute_opt(file.clone(), "read")?;
let readline = vm.get_attribute_opt(file, "readline")?;
let peek = vm.get_attribute_opt(&file, "peek")?;
let _readinto = vm.get_attribute_opt(&file, "readinto")?;
let read = vm.get_attribute_opt(&file, "read")?;
let readline = vm.get_attribute_opt(&file, "readline")?;
if read.is_none() || readline.is_none() {
return Err(vm.new_type_error("file must have 'read' and 'readline' attributes"));
}
@@ -1166,7 +1166,7 @@ mod _pickle {
if let Some(list) = obj.downcast_ref::<PyList>() {
list.borrow_vec_mut().extend(items);
} else {
match vm.get_attribute_opt(obj.clone(), "extend")? {
match vm.get_attribute_opt(&obj, "extend")? {
Some(extend) => {
extend.call((vm.ctx.new_list(items),), vm)?;
}
@@ -1521,9 +1521,7 @@ mod _pickle {
) -> PyResult<PyObjectRef> {
if args.is_empty()
&& cls.class().is(vm.ctx.types.type_type)
&& vm
.get_attribute_opt(cls.clone(), "__getinitargs__")?
.is_none()
&& vm.get_attribute_opt(&cls, "__getinitargs__")?.is_none()
{
return vm.call_method(&cls, "__new__", (cls.clone(),));
}
@@ -1531,7 +1529,7 @@ mod _pickle {
}
fn load_build(inst: &PyObject, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> {
if let Some(setstate) = vm.get_attribute_opt(inst.to_owned(), "__setstate__")? {
if let Some(setstate) = vm.get_attribute_opt(inst, "__setstate__")? {
setstate.call((state,), vm)?;
return Ok(());
}
@@ -1711,9 +1709,9 @@ mod _pickle {
#[pyfunction]
fn load(args: LoadArgs, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
let peek = vm.get_attribute_opt(args.file.clone(), "peek")?;
let read = vm.get_attribute_opt(args.file.clone(), "read")?;
let readline = vm.get_attribute_opt(args.file, "readline")?;
let peek = vm.get_attribute_opt(&args.file, "peek")?;
let read = vm.get_attribute_opt(&args.file, "read")?;
let readline = vm.get_attribute_opt(&args.file, "readline")?;
if read.is_none() || readline.is_none() {
return Err(vm.new_type_error("file must have 'read' and 'readline' attributes"));
}
@@ -2005,7 +2003,7 @@ mod _pickle {
impl Initializer for PyPickler {
type Args = PicklerNewArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let Some(mut out) = zelf.out.try_lock() else {
return Err(vm.new_runtime_error("Pickler.__init__() called recursively"));
};
@@ -2971,11 +2969,9 @@ mod _pickle {
rv = Some(reduce.call((obj.to_owned(),), vm)?);
} else if cls.fast_issubclass(vm.ctx.types.type_type) {
return self.save_global(obj, None, vm);
} else if let Some(reduce) =
vm.get_attribute_opt(obj.to_owned(), "__reduce_ex__")?
{
} else if let Some(reduce) = vm.get_attribute_opt(obj, "__reduce_ex__")? {
rv = Some(reduce.call((self.proto,), vm)?);
} else if let Some(reduce) = vm.get_attribute_opt(obj.to_owned(), "__reduce__")? {
} else if let Some(reduce) = vm.get_attribute_opt(obj, "__reduce__")? {
rv = Some(reduce.call((), vm)?);
} else {
return Err(new_pickling_error(
@@ -3103,7 +3099,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.to_owned(), "__name__")?
.get_attribute_opt(func, "__name__")?
.and_then(|o| {
o.downcast_ref::<PyStr>()
.map(|s| s.to_string_lossy().into_owned())
@@ -3119,7 +3115,7 @@ mod _pickle {
)));
}
let (cls, newargs, kwargs) = (parts[0].clone(), parts[1].clone(), parts[2].clone());
if vm.get_attribute_opt(cls.clone(), "__new__")?.is_none() {
if vm.get_attribute_opt(&cls, "__new__")?.is_none() {
return Err(new_pickling_error(
vm,
"first argument to __newobj_ex__() has no __new__",
@@ -3208,7 +3204,7 @@ mod _pickle {
return Err(vm.new_index_error("tuple index out of range"));
}
let cls = parts[0].clone();
if vm.get_attribute_opt(cls.clone(), "__new__")?.is_none() {
if vm.get_attribute_opt(&cls, "__new__")?.is_none() {
return Err(new_pickling_error(
vm,
"first argument to __newobj__() has no __new__",
@@ -3399,7 +3395,7 @@ mod _pickle {
.downcast()
.map_err(|_| new_pickling_error(vm, "expected a string as the global name"))?,
None => {
let value = match vm.get_attribute_opt(obj.to_owned(), "__qualname__")? {
let value = match vm.get_attribute_opt(obj, "__qualname__")? {
Some(q) if !vm.is_none(&q) => q,
_ => obj.get_attr("__name__", vm)?,
};
@@ -3596,7 +3592,7 @@ mod _pickle {
));
}
let sys_modules = vm.sys_module.get_attr("modules", vm)?;
let module_attr = vm.get_attribute_opt(obj.to_owned(), "__module__")?;
let module_attr = vm.get_attribute_opt(obj, "__module__")?;
let module_name: PyRef<PyStr> = match module_attr {
Some(m) if !vm.is_none(&m) => m
.downcast()
@@ -3731,8 +3727,8 @@ mod _pickle {
"persistent_id",
vm,
)?;
let reducer_override = vm.get_attribute_opt(zelf.to_owned().into(), "reducer_override")?;
let dispatch_table = vm.get_attribute_opt(zelf.to_owned().into(), "dispatch_table")?;
let reducer_override = vm.get_attribute_opt(zelf.as_object(), "reducer_override")?;
let dispatch_table = vm.get_attribute_opt(zelf.as_object(), "dispatch_table")?;
out.buf.clear();
out.frame_start = None;
+2 -2
View File
@@ -10,7 +10,7 @@ pub(crate) use _struct::module_def;
#[pymodule]
pub(crate) mod _struct {
use crate::vm::{
AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
AsObject, Py, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine,
buffer::{FormatSpec, new_struct_error, struct_error_type},
builtins::{PyBytes, PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef},
common::lock::{PyMappedRwLockReadGuard, PyRwLock, PyRwLockReadGuard},
@@ -283,7 +283,7 @@ pub(crate) mod _struct {
impl Initializer for PyStruct {
type Args = IntoStructFormatBytes;
fn init(zelf: PyRef<Self>, fmt: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, fmt: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// The format is read before anything is replaced, so a format that
// cannot be read leaves the object as it was.
let spec = fmt.format_spec(vm)?;
+2 -2
View File
@@ -6,7 +6,7 @@ pub(crate) use _random::module_def;
mod _random {
use crate::common::lock::PyMutex;
use crate::vm::{
PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
Py, PyObjectRef, PyPayload, PyResult, VirtualMachine,
builtins::{PyInt, PyTupleRef},
function::OptionalOption,
types::{Constructor, Initializer},
@@ -30,7 +30,7 @@ mod _random {
impl Initializer for PyRandom {
type Args = OptionalOption;
fn init(zelf: PyRef<Self>, x: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, x: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
zelf.seed(x, vm)
}
}
+2 -2
View File
@@ -1665,8 +1665,8 @@ mod _socket {
impl Initializer for PySocket {
type Args = SocketInitArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
Self::_init(&zelf, args, vm).map_err(|e| e.into_pyexception(vm))
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
Self::_init(zelf, args, vm).map_err(|e| e.into_pyexception(vm))
}
}
+1 -1
View File
@@ -389,7 +389,7 @@ mod _socket {
impl Initializer for PySocket {
type Args = SocketInitArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
let family = args.family.unwrap_or(AF_INET);
let kind = args.r#type.unwrap_or(SOCK_STREAM);
let proto = args.proto.unwrap_or(0);
+9 -5
View File
@@ -49,7 +49,11 @@ pub(crate) struct StartsEndsWithArgs {
impl StartsEndsWithArgs {
pub(crate) fn get_value(self, len: usize) -> (PyObjectRef, Option<Range<usize>>) {
let range = if self.start.is_some() || self.end.is_some() {
Some(adjust_indices(self.start, self.end, len))
Some(adjust_indices(
self.start.as_deref(),
self.end.as_deref(),
len,
))
} else {
None
};
@@ -88,12 +92,12 @@ fn saturate_to_isize(py_int: &Py<PyInt>) -> isize {
// help get optional string indices
pub(crate) fn adjust_indices(
start: Option<PyIntRef>,
end: Option<PyIntRef>,
start: Option<&Py<PyInt>>,
end: Option<&Py<PyInt>>,
len: usize,
) -> Range<usize> {
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);
let mut start = start.map_or(0, saturate_to_isize);
let mut end = end.map_or(len as isize, saturate_to_isize);
if end > len as isize {
end = len as isize;
} else if end < 0 {
+5 -5
View File
@@ -104,16 +104,16 @@ impl PyByteArray {
fn _setitem(
zelf: &Py<Self>,
needle: &PyObject,
value: PyObjectRef,
value: &PyObject,
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()
} else {
bytearray_from_object(vm, &value)?
bytearray_from_object(vm, value)?
};
if let Some(mut w) = zelf.try_resizable_opt() {
w.elements.setitem_by_slice(vm, slice, &items)
@@ -575,7 +575,7 @@ impl Py<PyByteArray> {
value: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult<()> {
PyByteArray::_setitem(self, needle, value, vm)
PyByteArray::_setitem(self, needle, &value, vm)
}
#[pymethod]
@@ -712,7 +712,7 @@ impl DefaultConstructor for PyByteArray {}
impl Initializer for PyByteArray {
type Args = ByteInnerNewOptions;
fn init(zelf: PyRef<Self>, options: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, options: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// First unpack bytearray and *then* get a lock to set it.
let mut inner = options.get_inner(bytearray_from_object, vm)?;
core::mem::swap(&mut *zelf.inner_mut(), &mut inner);
+11 -8
View File
@@ -52,13 +52,16 @@ impl PyPayload for PyClassMethod {
impl GetDescriptor for PyClassMethod {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
let (zelf, _obj) = Self::_unwrap(&zelf, obj, vm)?;
let cls = cls.unwrap_or_else(|| _obj.class().to_owned().into());
let (zelf, _obj) = Self::_unwrap(zelf, obj, vm)?;
let cls = match cls {
Some(cls) => cls.to_owned(),
None => _obj.class().to_owned().into(),
};
let callable = zelf.callable.lock().clone();
Ok(PyBoundMethod::new(cls, callable).into_ref(&vm.ctx).into())
}
@@ -88,7 +91,7 @@ impl Constructor for PyClassMethod {
impl Initializer for PyClassMethod {
type Args = PyObjectRef;
fn init(zelf: PyRef<Self>, callable: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, callable: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
*zelf.callable.lock() = callable.clone();
functools_wraps(zelf.as_object(), &callable, vm)
}
@@ -173,7 +176,7 @@ impl PyClassMethod {
#[pygetset]
fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyObjectRef {
let callable = self.callable.lock().clone();
if let Ok(Some(is_abstract)) = vm.get_attribute_opt(callable, "__isabstractmethod__") {
if let Ok(Some(is_abstract)) = vm.get_attribute_opt(&callable, "__isabstractmethod__") {
is_abstract
} else {
vm.ctx.new_bool(false).into()
@@ -239,7 +242,7 @@ pub(crate) fn functools_wraps(
identifier!(vm.ctx, __qualname__),
identifier!(vm.ctx, __doc__),
] {
if let Some(value) = vm.get_attribute_opt(wrapped.to_owned(), attr)? {
if let Some(value) = vm.get_attribute_opt(wrapped, attr)? {
wrapper.set_attr(attr, value, vm)?;
}
}
+34 -30
View File
@@ -70,12 +70,12 @@ impl core::fmt::Debug for PyMethodDescriptor {
impl GetDescriptor for PyMethodDescriptor {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
let descr = Self::_as_pyref(&zelf, vm).unwrap();
let descr = Self::_as_pyref(zelf, vm).unwrap();
let bound = match obj {
Some(obj) => {
if descr.method.flags.contains(PyMethodFlags::METHOD) {
@@ -83,7 +83,7 @@ impl GetDescriptor for PyMethodDescriptor {
.as_ref()
.is_none_or(|c| c.fast_isinstance(vm.ctx.types.type_type))
{
obj
obj.to_owned()
} else {
return Err(vm.new_type_error(format!(
"descriptor '{}' needs a type, not '{}', as arg 2",
@@ -94,11 +94,11 @@ impl GetDescriptor for PyMethodDescriptor {
} else if descr.method.flags.contains(PyMethodFlags::CLASS) {
obj.class().to_owned().into()
} else {
obj
obj.to_owned()
}
}
None if descr.method.flags.contains(PyMethodFlags::CLASS) => cls.unwrap(),
None => return Ok(zelf),
None if descr.method.flags.contains(PyMethodFlags::CLASS) => cls.unwrap().to_owned(),
None => return Ok(zelf.to_owned()),
};
Ok(descr.bind(bound, &vm.ctx).into())
}
@@ -220,15 +220,15 @@ impl core::fmt::Debug for PyClassMethodDescriptor {
impl GetDescriptor for PyClassMethodDescriptor {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
let descr = Self::_as_pyref(&zelf, vm).unwrap();
let descr = Self::_as_pyref(zelf, vm).unwrap();
let type_obj = match cls {
Some(typ) => typ,
None => match &obj {
Some(typ) => typ.to_owned(),
None => match obj {
Some(o) => o.class().to_owned().into(),
None => {
return Err(vm.new_type_error(format!(
@@ -277,7 +277,7 @@ impl Callable for PyClassMethodDescriptor {
zelf.common.typ.name()
)));
};
let bound = Self::descr_get(zelf.to_owned().into(), None, Some(owner), vm)?;
let bound = Self::descr_get(zelf.as_object(), None, Some(&owner), vm)?;
args.args.remove(0);
bound.call(args, vm)
}
@@ -417,7 +417,7 @@ impl PyPayload for PyMemberDescriptor {
}
fn calculate_qualname(descr: &PyDescriptorOwned, vm: &VirtualMachine) -> PyResult<Option<String>> {
if let Some(qualname) = vm.get_attribute_opt(descr.typ.clone().into(), "__qualname__")? {
if let Some(qualname) = vm.get_attribute_opt(descr.typ.as_object(), "__qualname__")? {
let str = qualname.downcast::<PyStr>().map_err(|_| {
vm.new_type_error("<descriptor>.__objclass__.__qualname__ is not a unicode object")
})?;
@@ -581,12 +581,12 @@ impl Representable for PyMemberDescriptor {
impl GetDescriptor for PyMemberDescriptor {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
_cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
_cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
let descr = Self::_as_pyref(&zelf, vm)?;
let descr = Self::_as_pyref(zelf, vm)?;
match obj {
Some(x) => {
if !x.class().fast_issubclass(&descr.common.typ) {
@@ -597,9 +597,9 @@ impl GetDescriptor for PyMemberDescriptor {
x.class().name()
)));
}
descr.member.get(x, vm)
descr.member.get(x.to_owned(), vm)
}
None => Ok(zelf),
None => Ok(zelf.to_owned()),
}
}
}
@@ -774,7 +774,7 @@ impl SlotFunc {
pub fn call(&self, obj: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult {
match self {
Self::Init(func) => {
func(obj, args, vm)?;
func(&obj, args, vm)?;
Ok(vm.ctx.none())
}
Self::Hash(func) => {
@@ -848,7 +848,7 @@ impl SlotFunc {
} else {
Some(instance)
};
func(obj, instance_opt, owner, vm)
func(&obj, instance_opt.as_deref(), owner.as_deref(), vm)
}
Self::DescrSet(func) => {
let (instance, value): (PyObjectRef, PyObjectRef) = args.bind(vm)?;
@@ -1011,16 +1011,20 @@ impl PyPayload for PyWrapper {
impl GetDescriptor for PyWrapper {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
_cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
_cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
match obj {
None => Ok(zelf),
None => Ok(zelf.to_owned()),
Some(obj) => {
let zelf = zelf.downcast::<Self>().unwrap();
Ok(PyMethodWrapper { wrapper: zelf, obj }.into_pyobject(vm))
let zelf = zelf.to_owned().downcast::<Self>().unwrap();
Ok(PyMethodWrapper {
wrapper: zelf,
obj: obj.to_owned(),
}
.into_pyobject(vm))
}
}
}
+4 -8
View File
@@ -166,7 +166,7 @@ impl PyDict {
Err(e) => return Err(e),
};
if !has_keys {
return self.merge_from_seq2(other, override_existing, vm);
return self.merge_from_seq2(&other, override_existing, vm);
}
Ok(())
}
@@ -252,7 +252,7 @@ impl PyDict {
pub fn merge_from_seq2(
&self,
seq2: PyObjectRef,
seq2: &PyObject,
override_existing: bool,
vm: &VirtualMachine,
) -> PyResult<()> {
@@ -628,11 +628,7 @@ impl DefaultConstructor for PyDict {}
impl Initializer for PyDict {
type Args = (OptionalArg<PyObjectRef>, KwArgs);
fn init(
zelf: PyRef<Self>,
(dict_obj, kwargs): Self::Args,
vm: &VirtualMachine,
) -> PyResult<()> {
fn init(zelf: &Py<Self>, (dict_obj, kwargs): Self::Args, vm: &VirtualMachine) -> PyResult<()> {
zelf.update(dict_obj, kwargs, vm)
}
}
@@ -1822,7 +1818,7 @@ fn vectorcall_dict(
let zelf: &Py<PyType> = zelf_obj.downcast_ref().unwrap();
let obj = PyDict::default().into_ref_with_type(vm, zelf.to_owned())?;
let func_args = FuncArgs::from_vectorcall_owned(args, nargs, kwnames);
PyDict::slot_init(obj.clone().into(), func_args, vm)?;
PyDict::slot_init(obj.as_object(), func_args, vm)?;
Ok(obj.into())
}
+1 -1
View File
@@ -167,7 +167,7 @@ impl FrameLocalsProxy {
#[pymethod]
fn setdefault(&self, key: PyObjectRef, default: OptionalArg, vm: &VirtualMachine) -> PyResult {
self.frame
.framelocalsproxy_setdefault(key, default.unwrap_or_none(vm), vm)
.framelocalsproxy_setdefault(&key, default.unwrap_or_none(vm), vm)
}
#[pymethod]
+15 -13
View File
@@ -1292,16 +1292,18 @@ impl PyFunction {
impl GetDescriptor for PyFunction {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
let (_zelf, obj) = Self::_unwrap(&zelf, obj, vm)?;
Ok(if vm.is_none(&obj) && !Self::_cls_is(&cls, obj.class()) {
zelf
let (_zelf, obj) = Self::_unwrap(zelf, obj, vm)?;
Ok(if vm.is_none(obj) && !Self::_cls_is(&cls, obj.class()) {
zelf.to_owned()
} else {
PyBoundMethod::new(obj, zelf).into_ref(&vm.ctx).into()
PyBoundMethod::new(obj.to_owned(), zelf.to_owned())
.into_ref(&vm.ctx)
.into()
})
}
}
@@ -1443,12 +1445,12 @@ impl GetAttr for PyBoundMethod {
impl GetDescriptor for PyBoundMethod {
fn descr_get(
zelf: PyObjectRef,
_obj: Option<PyObjectRef>,
_cls: Option<PyObjectRef>,
zelf: &PyObject,
_obj: Option<&PyObject>,
_cls: Option<&PyObject>,
_vm: &VirtualMachine,
) -> PyResult {
Ok(zelf)
Ok(zelf.to_owned())
}
}
@@ -1589,11 +1591,11 @@ impl Representable for PyBoundMethod {
#[inline]
fn repr_wtf8(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<Wtf8Buf> {
let func_name = if let Some(qname) =
vm.get_attribute_opt(zelf.function.clone(), identifier!(vm, __qualname__))?
vm.get_attribute_opt(&zelf.function, identifier!(vm, __qualname__))?
{
Some(qname)
} else {
vm.get_attribute_opt(zelf.function.clone(), identifier!(vm, __name__))?
vm.get_attribute_opt(&zelf.function, identifier!(vm, __name__))?
};
let func_name: Option<PyStrRef> = func_name.and_then(|o| o.downcast().ok());
let object_repr = zelf.object.repr(vm)?;
+7 -7
View File
@@ -123,19 +123,19 @@ impl PyGenericAlias {
}
if vm
.get_attribute_opt(obj.to_owned(), identifier!(vm, __origin__))?
.get_attribute_opt(obj, identifier!(vm, __origin__))?
.is_some()
&& vm
.get_attribute_opt(obj.to_owned(), identifier!(vm, __args__))?
.get_attribute_opt(obj, identifier!(vm, __args__))?
.is_some()
{
return Ok(obj.repr(vm)?.to_string());
}
match (
vm.get_attribute_opt(obj.to_owned(), identifier!(vm, __qualname__))?
vm.get_attribute_opt(obj, identifier!(vm, __qualname__))?
.and_then(|o| o.downcast_ref::<PyStr>().map(|n| n.to_string())),
vm.get_attribute_opt(obj.to_owned(), identifier!(vm, __module__))?
vm.get_attribute_opt(obj, identifier!(vm, __module__))?
.and_then(|o| o.downcast_ref::<PyStr>().map(|m| m.to_string())),
) {
(None, _) | (_, None) => Ok(obj.repr(vm)?.to_string()),
@@ -147,7 +147,7 @@ impl PyGenericAlias {
}
}
fn repr_arg(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<String> {
fn repr_arg(obj: &PyObject, vm: &VirtualMachine) -> PyResult<String> {
// ParamSpec args can be lists - format their items with repr_item
if obj.class().is(vm.ctx.types.list_type) {
let list = obj.downcast_ref::<crate::builtins::PyList>().unwrap();
@@ -164,7 +164,7 @@ impl PyGenericAlias {
}
Ok(format!("[{}]", parts.join(", ")))
} else {
repr_item(&obj, vm)
repr_item(obj, vm)
}
}
@@ -176,7 +176,7 @@ impl PyGenericAlias {
} else {
self.args
.iter()
.map(|o| repr_arg(o.clone(), vm))
.map(|o| repr_arg(o, vm))
.collect::<PyResult<Vec<_>>>()?
.join(", ")
}
+6 -6
View File
@@ -56,17 +56,17 @@ impl PyPayload for PyGetSet {
impl GetDescriptor for PyGetSet {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
_cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
_cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
let (zelf, obj) = match Self::_check(&zelf, obj, vm) {
let (zelf, obj) = match Self::_check(zelf, obj, vm) {
Some(obj) => obj,
None => return Ok(zelf),
None => return Ok(zelf.to_owned()),
};
if let Some(ref f) = zelf.getter {
f(vm, obj)
f(vm, obj.to_owned())
} else {
Err(vm.new_attribute_error(format!(
"attribute '{}' of '{}' objects is not readable",
+8 -8
View File
@@ -409,7 +409,7 @@ impl PyList {
let version_before = self.mutation_counter.load(Ordering::Relaxed);
(core::mem::take(&mut *guard), version_before)
};
let res = do_sort(vm, &mut elements, options.key, options.reverse);
let res = do_sort(vm, &mut elements, options.key.as_deref(), options.reverse);
let mutated = {
let mut guard = self.elements.write();
let mutated = self.mutation_counter.load(Ordering::Relaxed) != version_before;
@@ -484,9 +484,9 @@ impl Constructor for PyList {
impl Initializer for PyList {
type Args = OptionalArg<PyObjectRef>;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let list_type = vm.ctx.types.list_type;
let cls = zelf.class().to_owned();
let cls = zelf.class();
let uses_list_new = {
let cls_new = cls.slots.new.load().map(crate::types::fn_addr);
let list_new = list_type.slots.new.load().map(crate::types::fn_addr);
@@ -503,10 +503,10 @@ impl Initializer for PyList {
}
}
};
Self::init(zelf.try_into_value(vm)?, iterable, vm)
Self::init(zelf.try_to_ref(vm)?, iterable, vm)
}
fn init(zelf: PyRef<Self>, iterable: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, iterable: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let mut elements = if let OptionalArg::Present(iterable) = iterable {
vm.extract_elements_sized(&iterable, &|| 0, Ok)?
} else {
@@ -882,10 +882,10 @@ where
fn do_sort(
vm: &VirtualMachine,
values: &mut Vec<PyObjectRef>,
key_func: Option<PyObjectRef>,
key_func: Option<&PyObject>,
reverse: bool,
) -> PyResult<()> {
if let Some(ref key_func) = key_func {
if let Some(key_func) = key_func {
let mut items = values
.iter()
.map(|x| Ok((x.clone(), key_func.call((x.clone(),), vm)?)))
@@ -1027,7 +1027,7 @@ fn vectorcall_list(
let zelf: &Py<PyType> = zelf_obj.downcast_ref().unwrap();
let obj = PyList::default().into_ref_with_type(vm, zelf.to_owned())?;
let func_args = FuncArgs::from_vectorcall_owned(args, nargs, kwnames);
PyList::slot_init(obj.clone().into(), func_args, vm)?;
PyList::slot_init(obj.as_object(), func_args, vm)?;
Ok(obj.into())
}
+1 -1
View File
@@ -427,7 +427,7 @@ impl PyModule {
impl Initializer for PyModule {
type Args = ModuleInitArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
debug_assert!(
zelf.class()
.slots
+1 -1
View File
@@ -89,7 +89,7 @@ impl PyNamespace {
impl Initializer for PyNamespace {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// SimpleNamespace accepts 0 or 1 positional argument (a mapping)
if args.args.len() > 1 {
return Err(vm.new_type_error(format!(
+3 -3
View File
@@ -114,7 +114,7 @@ impl Initializer for PyBaseObject {
type Args = FuncArgs;
// object_init: excess_args validation
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
if args.is_empty() {
return Ok(());
}
@@ -152,7 +152,7 @@ impl Initializer for PyBaseObject {
Ok(())
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
@@ -505,7 +505,7 @@ impl PyBaseObject {
#[pymethod]
fn __reduce_ex__(zelf: PyObjectRef, protocol: usize, vm: &VirtualMachine) -> PyResult {
let __reduce__ = identifier!(vm, __reduce__);
if let Some(reduce) = vm.get_attribute_opt(zelf.clone(), __reduce__)? {
if let Some(reduce) = vm.get_attribute_opt(&zelf, __reduce__)? {
let object_reduce = vm.ctx.types.object_type.get_attr(__reduce__).unwrap();
let typ_obj: PyObjectRef = zelf.class().to_owned().into();
let class_reduce = typ_obj.get_attr(__reduce__, vm)?;
+10 -10
View File
@@ -45,22 +45,22 @@ pub struct PropertyArgs {
impl GetDescriptor for PyProperty {
fn descr_get(
zelf_obj: PyObjectRef,
obj: Option<PyObjectRef>,
_cls: Option<PyObjectRef>,
zelf_obj: &PyObject,
obj: Option<&PyObject>,
_cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
let (zelf, obj) = Self::_unwrap(&zelf_obj, obj, vm)?;
if vm.is_none(&obj) {
return Ok(zelf_obj);
let (zelf, obj) = Self::_unwrap(zelf_obj, obj, vm)?;
if vm.is_none(obj) {
return Ok(zelf_obj.to_owned());
}
// Clone and release lock before calling Python code to prevent deadlock
let value = zelf.getter.read().clone();
if let Some(getter) = value {
getter.call((obj,), vm)
getter.call((obj.to_owned(),), vm)
} else {
let error_msg = zelf.format_property_error(&obj, "getter", vm)?;
let error_msg = zelf.format_property_error(obj, "getter", vm)?;
Err(vm.new_attribute_error(error_msg))
}
}
@@ -235,7 +235,7 @@ impl PyProperty {
// Create new property using py_new and init
let new_prop = Self::slot_new(zelf.class().to_owned(), FuncArgs::default(), vm)?;
let new_prop_ref = new_prop.downcast::<Self>().unwrap();
Self::init(new_prop_ref.clone(), args, vm)?;
Self::init(&new_prop_ref, args, vm)?;
// Copy the name if it exists
let value = zelf.name.read().clone();
@@ -364,7 +364,7 @@ impl Constructor for PyProperty {
impl Initializer for PyProperty {
type Args = PropertyArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// Set doc and getter_doc flag
let mut getter_doc = false;
+2 -2
View File
@@ -905,7 +905,7 @@ impl DefaultConstructor for PySet {}
impl Initializer for PySet {
type Args = OptionalArg<PyObjectRef>;
fn init(zelf: PyRef<Self>, iterable: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, iterable: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
zelf.clear();
if let OptionalArg::Present(it) = iterable {
zelf.update(PosArgs::new(vec![it]), vm)?;
@@ -1621,7 +1621,7 @@ fn vectorcall_set(
let zelf: &Py<PyType> = zelf_obj.downcast_ref().unwrap();
let obj = PySet::default().into_ref_with_type(vm, zelf.to_owned())?;
let func_args = FuncArgs::from_vectorcall_owned(args, nargs, kwnames);
PySet::slot_init(obj.clone().into(), func_args, vm)?;
PySet::slot_init(obj.as_object(), func_args, vm)?;
Ok(obj.into())
}
+7 -7
View File
@@ -5,7 +5,7 @@ use super::{
},
};
use crate::{
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
class::{PyClassDef, PyClassImpl},
common::lock::PyMutex,
function::{FuncArgs, PySetterValue},
@@ -27,12 +27,12 @@ impl PyPayload for PyStaticMethod {
impl GetDescriptor for PyStaticMethod {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
_cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
_cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
let (zelf, _obj) = Self::_unwrap(&zelf, obj, vm)?;
let (zelf, _obj) = Self::_unwrap(zelf, obj, vm)?;
Ok(zelf.callable.lock().clone())
}
}
@@ -83,7 +83,7 @@ impl PyStaticMethod {
impl Initializer for PyStaticMethod {
type Args = PyObjectRef;
fn init(zelf: PyRef<Self>, callable: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, callable: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
*zelf.callable.lock() = callable.clone();
functools_wraps(zelf.as_object(), &callable, vm)
}
@@ -162,7 +162,7 @@ impl PyStaticMethod {
fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyObjectRef {
let callable = self.callable.lock().clone();
if let Ok(Some(is_abstract)) = vm.get_attribute_opt(callable, "__isabstractmethod__") {
if let Ok(Some(is_abstract)) = vm.get_attribute_opt(&callable, "__isabstractmethod__") {
is_abstract
} else {
vm.ctx.new_bool(false).into()
+5 -5
View File
@@ -1047,7 +1047,7 @@ impl PyStr {
}
pub fn __mod__(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult<Wtf8Buf> {
cformat_string(vm, self.as_wtf8(), values)
cformat_string(vm, self.as_wtf8(), &values)
}
#[pymethod]
@@ -1557,7 +1557,7 @@ impl PyStr {
#[pymethod]
fn encode(zelf: PyRef<Self>, args: EncodeArgs, vm: &VirtualMachine) -> PyResult<PyBytesRef> {
encode_string(zelf, args.encoding, args.errors, vm)
encode_string(zelf, args.encoding.as_deref(), args.errors, vm)
}
#[pymethod]
@@ -1746,11 +1746,11 @@ struct EncodeArgs {
pub(crate) fn encode_string(
s: PyStrRef,
encoding: Option<PyUtf8StrRef>,
encoding: Option<&Py<PyUtf8Str>>,
errors: Option<PyUtf8StrRef>,
vm: &VirtualMachine,
) -> PyResult<PyBytesRef> {
let encoding = match encoding.as_ref() {
let encoding = match encoding {
None => crate::codecs::DEFAULT_ENCODING,
Some(s) => s.as_str(),
};
@@ -1859,7 +1859,7 @@ pub(crate) struct FindArgs {
impl FindArgs {
fn get_value(self, len: usize) -> (PyStrRef, core::ops::Range<usize>) {
let range = adjust_indices(self.start, self.end, len);
let range = adjust_indices(self.start.as_deref(), self.end.as_deref(), len);
(self.sub, range)
}
}
+16 -12
View File
@@ -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, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine,
builtins::function::PyCell,
class::PyClassImpl,
common::lock::PyRwLock,
@@ -71,7 +71,7 @@ impl Initializer for PySuper {
type Args = InitArgs;
fn init(
zelf: PyRef<Self>,
zelf: &Py<Self>,
Self::Args { py_type, py_obj }: Self::Args,
vm: &VirtualMachine,
) -> PyResult<()> {
@@ -203,8 +203,12 @@ impl GetAttr for PySuper {
.call_get_descriptor_specific(
&descr,
// Only pass 'obj' param if this is instance-mode super (See https://bugs.python.org/issue743267)
if obj.is(&start_type) { None } else { Some(obj) },
Some(start_type.as_object().to_owned()),
if obj.is(&start_type) {
None
} else {
Some(&obj)
},
Some(start_type.as_object()),
)
.unwrap_or(Ok(descr));
}
@@ -215,26 +219,26 @@ impl GetAttr for PySuper {
impl GetDescriptor for PySuper {
fn descr_get(
zelf_obj: PyObjectRef,
obj: Option<PyObjectRef>,
_cls: Option<PyObjectRef>,
zelf_obj: &PyObject,
obj: Option<&PyObject>,
_cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
let (zelf, obj) = Self::_unwrap(&zelf_obj, obj, vm)?;
if vm.is_none(&obj) || zelf.inner.read().obj.is_some() {
return Ok(zelf_obj);
let (zelf, obj) = Self::_unwrap(zelf_obj, obj, vm)?;
if vm.is_none(obj) || zelf.inner.read().obj.is_some() {
return Ok(zelf_obj.to_owned());
}
let zelf_class = zelf.as_object().class();
if zelf_class.is(vm.ctx.types.super_type) {
let typ = zelf.inner.read().typ.clone();
Ok(Self {
inner: PyRwLock::new(PySuperInner::new(typ, obj, vm)?),
inner: PyRwLock::new(PySuperInner::new(typ, obj.to_owned(), vm)?),
}
.into_ref(&vm.ctx)
.into())
} else {
let typ = zelf.inner.read().typ.clone();
PyType::call(zelf.class(), (typ, obj).into_args(vm), vm)
PyType::call(zelf.class(), (typ, obj.to_owned()).into_args(vm), vm)
}
}
}
+13 -9
View File
@@ -2450,7 +2450,7 @@ impl Constructor for PyType {
for obj in bases.iter() {
if obj.downcast_ref::<Self>().is_none() {
if vm
.get_attribute_opt(obj.clone(), identifier!(vm, __mro_entries__))?
.get_attribute_opt(obj, identifier!(vm, __mro_entries__))?
.is_some()
{
return Err(vm.new_type_error(
@@ -2958,7 +2958,7 @@ impl Initializer for PyType {
type Args = FuncArgs;
// type_init
fn slot_init(_zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(_zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
// type.__init__() takes 1 or 3 arguments
if args.args.len() == 1 && !args.kwargs.is_empty() {
return Err(vm.new_type_error("type.__init__() takes no keyword arguments"));
@@ -2969,7 +2969,7 @@ impl Initializer for PyType {
Ok(())
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
@@ -3002,8 +3002,12 @@ impl GetAttr for PyType {
if has_descr_set {
let descr_get = attr_class.slots.descr_get.load();
if let Some(descr_get) = descr_get {
let mcl = mcl.to_owned().into();
return descr_get(attr.clone(), Some(zelf.to_owned().into()), Some(mcl), vm);
return descr_get(
attr.as_object(),
Some(zelf.as_object()),
Some(mcl.as_object()),
vm,
);
}
}
}
@@ -3013,7 +3017,7 @@ impl GetAttr for PyType {
if let Some(attr) = zelf_attr {
let descr_get = attr.class().slots.descr_get.load();
if let Some(descr_get) = descr_get {
descr_get(attr, None, Some(zelf.to_owned().into()), vm)
descr_get(attr.as_object(), None, Some(zelf.as_object()), vm)
} else {
Ok(attr)
}
@@ -3056,7 +3060,7 @@ impl Py<PyType> {
// If it's a descriptor, call its __get__ method
let descr_get = doc_attr.class().slots.descr_get.load();
if let Some(descr_get) = descr_get {
descr_get(doc_attr, None, Some(self.to_owned().into()), vm)
descr_get(doc_attr.as_object(), None, Some(self.as_object()), vm)
} else {
Ok(doc_attr)
}
@@ -3236,7 +3240,7 @@ impl Callable for PyType {
}
if let Some(init_method) = obj.class().slots.init.load() {
init_method(obj.clone(), init_args, vm)?;
init_method(&obj, init_args, vm)?;
}
Ok(obj)
}
@@ -3313,7 +3317,7 @@ fn subtype_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult {
if let Some(base_type) = base {
if let Some(descr) = get_dict_descriptor(&base_type, vm) {
// Call the descriptor's tp_descr_get
vm.call_get_descriptor(&descr, obj.clone())
vm.call_get_descriptor(&descr, &obj)
.unwrap_or_else(|| Err(raise_dict_descriptor_error(&obj, vm)))
} else {
Err(raise_dict_descriptor_error(&obj, vm))
+4 -4
View File
@@ -65,19 +65,19 @@ impl PyUnion {
}
if vm
.get_attribute_opt(obj.to_owned(), identifier!(vm, __origin__))?
.get_attribute_opt(obj, identifier!(vm, __origin__))?
.is_some()
&& vm
.get_attribute_opt(obj.to_owned(), identifier!(vm, __args__))?
.get_attribute_opt(obj, identifier!(vm, __args__))?
.is_some()
{
return Ok(obj.repr(vm)?.to_string());
}
match (
vm.get_attribute_opt(obj.to_owned(), identifier!(vm, __qualname__))?
vm.get_attribute_opt(obj, identifier!(vm, __qualname__))?
.and_then(|o| o.downcast_ref::<PyStr>().map(|n| n.to_string())),
vm.get_attribute_opt(obj.to_owned(), identifier!(vm, __module__))?
vm.get_attribute_opt(obj, identifier!(vm, __module__))?
.and_then(|o| o.downcast_ref::<PyStr>().map(|m| m.to_string())),
) {
(None, _) | (_, None) => Ok(obj.repr(vm)?.to_string()),
+2 -2
View File
@@ -4,7 +4,7 @@ use crate::common::{
hash::{self, PyHash},
};
use crate::{
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine,
class::PyClassImpl,
function::{FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue},
types::{
@@ -67,7 +67,7 @@ impl Initializer for PyWeak {
type Args = WeakNewArgs;
// weakref_tp_init: accepts args but does nothing (all init done in slot_new)
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
Ok(())
}
}
+3 -3
View File
@@ -64,7 +64,7 @@ impl ByteInnerNewOptions {
errors: OptionalArg<PyUtf8StrRef>,
vm: &VirtualMachine,
) -> PyResult<PyBytesInner> {
let bytes = pystr::encode_string(s, Some(encoding), errors.into_option(), vm)?;
let bytes = pystr::encode_string(s, Some(&encoding), errors.into_option(), vm)?;
Ok(bytes.as_bytes().to_vec().into())
}
@@ -211,7 +211,7 @@ impl ByteInnerFindOptions {
vm: &VirtualMachine,
) -> PyResult<(Vec<u8>, core::ops::Range<usize>)> {
let sub = self.sub.into_vec(vm)?;
let range = anystr::adjust_indices(self.start, self.end, len);
let range = anystr::adjust_indices(self.start.as_deref(), self.end.as_deref(), len);
Ok((sub, range))
}
}
@@ -1024,7 +1024,7 @@ impl PyBytesInner {
}
pub fn cformat(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
cformat_bytes(vm, self.elements.as_slice(), values)
cformat_bytes(vm, self.elements.as_slice(), &values)
}
pub fn mul(&self, n: isize, vm: &VirtualMachine) -> PyResult<Vec<u8>> {
+22 -15
View File
@@ -362,7 +362,7 @@ fn specifier_error(vm: &VirtualMachine) -> PyBaseExceptionRef {
pub(crate) fn cformat_bytes(
vm: &VirtualMachine,
format_string: &[u8],
values_obj: PyObjectRef,
values_obj: &PyObject,
) -> PyResult<Vec<u8>> {
let mut format = CFormatBytes::parse_from_bytes(format_string)
.map_err(|err| vm.new_value_error(err.to_string()))?;
@@ -420,12 +420,16 @@ pub(crate) fn cformat_bytes(
}
// tuple
let values = if let Some(tup) = values_obj.downcast_ref::<tuple::PyTuple>() {
tup.as_slice()
} else {
core::slice::from_ref(&values_obj)
};
let mut value_iter = values.iter().map(|v| &**v);
let mut slice_iter;
let mut once_iter;
let mut value_iter: &mut dyn Iterator<Item = &PyObject> =
if let Some(tup) = values_obj.downcast_ref::<tuple::PyTuple>() {
slice_iter = tup.as_slice().iter().map(|v| &**v);
&mut slice_iter
} else {
once_iter = core::iter::once(values_obj);
&mut once_iter
};
for (_, part) in format {
match part {
@@ -460,7 +464,7 @@ pub(crate) fn cformat_bytes(
pub(crate) fn cformat_string(
vm: &VirtualMachine,
format_string: &Wtf8,
values_obj: PyObjectRef,
values_obj: &PyObject,
) -> PyResult<Wtf8Buf> {
let format = CFormatWtf8::parse_from_wtf8(format_string)
.map_err(|err| vm.new_value_error(err.to_string()))?;
@@ -516,13 +520,16 @@ pub(crate) fn cformat_string(
}
// tuple
let values = if let Some(tup) = values_obj.downcast_ref::<tuple::PyTuple>() {
tup.as_slice()
} else {
core::slice::from_ref(&values_obj)
};
let mut value_iter = values.iter().map(|v| &**v);
let mut slice_iter;
let mut once_iter;
let mut value_iter: &mut dyn Iterator<Item = &PyObject> =
if let Some(tup) = values_obj.downcast_ref::<tuple::PyTuple>() {
slice_iter = tup.as_slice().iter().map(|v| &**v);
&mut slice_iter
} else {
once_iter = core::iter::once(values_obj);
&mut once_iter
};
for (_, part) in format {
match part {
+2 -2
View File
@@ -72,7 +72,7 @@ impl PyCodec {
}
pub fn is_text_codec(&self, vm: &VirtualMachine) -> PyResult<bool> {
let is_text = vm.get_attribute_opt(self.0.clone().into(), "_is_text_encoding")?;
let is_text = vm.get_attribute_opt(self.0.as_object(), "_is_text_encoding")?;
is_text.map_or(Ok(true), |is_text| is_text.try_to_bool(vm))
}
@@ -215,7 +215,7 @@ impl CodecsRegistry {
Ok(())
}
pub fn unregister(&self, search_function: PyObjectRef) {
pub fn unregister(&self, search_function: &PyObject) {
let mut inner = self.inner.write();
// Do nothing if search_path is not created yet or was cleared.
if inner.search_path.is_empty() {
+2 -2
View File
@@ -383,7 +383,7 @@ pub(super) mod types {
impl Initializer for PyBaseExceptionGroup {
type Args = FuncArgs;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
if !args.kwargs.is_empty() {
return Err(vm.new_type_error(format!(
"{} does not take keyword arguments",
@@ -393,7 +393,7 @@ pub(super) mod types {
PyBaseException::slot_init(zelf, args, vm)
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is overridden")
}
}
+32 -32
View File
@@ -99,7 +99,7 @@ impl VirtualMachine {
// These functions are natively free function in CPython - not methods of PyException
/// Print exception chain by calling sys.excepthook
pub fn print_exception(&self, exc: PyBaseExceptionRef) {
pub fn print_exception(&self, exc: &Py<PyBaseException>) {
let vm = self;
let write_fallback = |exc, errstr| {
if let Ok(stderr) = sys::get_stderr(vm) {
@@ -113,13 +113,13 @@ impl VirtualMachine {
}
};
if let Ok(excepthook) = vm.sys_module.get_attr("excepthook", vm) {
let (exc_type, exc_val, exc_tb) = vm.split_exception(exc.clone());
let (exc_type, exc_val, exc_tb) = vm.split_exception(exc.to_owned());
if let Err(eh_exc) = excepthook.call((exc_type, exc_val, exc_tb), vm) {
write_fallback(&eh_exc, "Error in sys.excepthook:");
write_fallback(&exc, "Original exception was:");
write_fallback(exc, "Original exception was:");
}
} else {
write_fallback(&exc, "missing sys.excepthook");
write_fallback(exc, "missing sys.excepthook");
}
}
@@ -865,7 +865,7 @@ impl Constructor for PyBaseException {
impl Initializer for PyBaseException {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
*zelf.args.write() = PyTuple::new_ref(args.args, &vm.ctx);
Ok(())
}
@@ -1810,20 +1810,20 @@ pub(super) mod types {
impl Initializer for PySystemExit {
type Args = FuncArgs;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
// Call BaseException_init first (handles args)
let code = match args.args.len() {
0 => vm.ctx.none(),
1 => args.args[0].clone(),
_ => vm.ctx.new_tuple(args.args.clone()).into(),
};
PyBaseException::slot_init(zelf.clone(), args, vm)?;
PyBaseException::slot_init(zelf, args, vm)?;
let exc: &Py<Self> = zelf.downcast_ref::<Self>().unwrap();
exc.code.swap_to_temporary_refs(Some(code), vm);
Ok(())
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
@@ -1898,18 +1898,18 @@ pub(super) mod types {
impl Initializer for PyStopIteration {
type Args = FuncArgs;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let value = match args.args.len() {
0 => vm.ctx.none(),
_ => args.args[0].clone(),
};
PyBaseException::slot_init(zelf.clone(), args, vm)?;
PyBaseException::slot_init(zelf, args, vm)?;
let exc: &Py<Self> = zelf.downcast_ref::<Self>().unwrap();
exc.value.swap_to_temporary_refs(Some(value), vm);
Ok(())
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
@@ -1998,7 +1998,7 @@ pub(super) mod types {
impl Initializer for PyAttributeError {
type Args = FuncArgs;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
// Only 'name' and 'obj' kwargs are allowed
let mut kwargs = args.kwargs.clone();
let name = kwargs.swap_remove("name");
@@ -2014,7 +2014,7 @@ pub(super) mod types {
// Pass args without kwargs to BaseException_init
let base_args = FuncArgs::new(args.args, KwArgs::default());
PyBaseException::slot_init(zelf.clone(), base_args, vm)?;
PyBaseException::slot_init(zelf, base_args, vm)?;
// Set attributes
set_attrs!(zelf, vm,
@@ -2024,7 +2024,7 @@ pub(super) mod types {
Ok(())
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
@@ -2066,7 +2066,7 @@ pub(super) mod types {
impl Initializer for PyImportError {
type Args = FuncArgs;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
// Only 'name', 'path', 'name_from' kwargs are allowed
let mut kwargs = args.kwargs.clone();
let name = kwargs.swap_remove("name");
@@ -2099,7 +2099,7 @@ pub(super) mod types {
PyBaseException::slot_init(zelf, args, vm)
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
@@ -2183,7 +2183,7 @@ pub(super) mod types {
impl Initializer for PyNameError {
type Args = FuncArgs;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
// Only 'name' kwarg is allowed
let mut kwargs = args.kwargs.clone();
let name = kwargs.swap_remove("name");
@@ -2198,7 +2198,7 @@ pub(super) mod types {
// Pass args without kwargs to BaseException_init
let base_args = FuncArgs::new(args.args, KwArgs::default());
PyBaseException::slot_init(zelf.clone(), base_args, vm)?;
PyBaseException::slot_init(zelf, base_args, vm)?;
// Set name attribute if provided
if let Some(name) = name {
@@ -2207,7 +2207,7 @@ pub(super) mod types {
Ok(())
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
@@ -2357,7 +2357,7 @@ pub(super) mod types {
}
let payload = Self::py_new(&cls, args.clone(), vm)?;
let obj = payload.into_ref_with_type_lazy_dict(vm, cls)?;
oserror_init(obj.as_object().to_owned(), args, vm)?;
oserror_init(obj.as_object(), args, vm)?;
Ok(obj.into())
}
}
@@ -2365,14 +2365,14 @@ pub(super) mod types {
fn oserror_use_init(cls: &Py<PyType>) -> bool {
let init = cls.slots.init.load();
let new = cls.slots.new.load();
let slot_init: fn(PyObjectRef, FuncArgs, &VirtualMachine) -> PyResult<()> =
let slot_init: fn(&PyObject, FuncArgs, &VirtualMachine) -> PyResult<()> =
PyOSError::slot_init;
let slot_new: fn(PyTypeRef, FuncArgs, &VirtualMachine) -> PyResult = PyOSError::slot_new;
!matches!(init, Some(f) if core::ptr::fn_addr_eq(f, slot_init))
&& matches!(new, Some(f) if core::ptr::fn_addr_eq(f, slot_new))
}
fn oserror_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn oserror_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let len = args.args.len();
let mut new_args = args;
@@ -2458,7 +2458,7 @@ pub(super) mod types {
impl Initializer for PyOSError {
type Args = FuncArgs;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
if !oserror_use_init(zelf.class()) {
return Ok(());
}
@@ -2471,7 +2471,7 @@ pub(super) mod types {
oserror_init(zelf, args, vm)
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
@@ -2899,7 +2899,7 @@ pub(super) mod types {
impl Initializer for PySyntaxError {
type Args = FuncArgs;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let len = args.args.len();
let new_args = args;
@@ -2954,7 +2954,7 @@ pub(super) mod types {
PyBaseException::slot_init(zelf, new_args, vm)
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
@@ -3138,7 +3138,7 @@ pub(super) mod types {
impl Initializer for PyUnicodeDecodeError {
type Args = FuncArgs;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
parse_tuple_arity(&args, 5, vm)?;
type Args = (PyStrRef, ArgBytesLike, isize, isize, PyStrRef);
let (encoding, object, start, end, reason): Args = args.bind(vm)?;
@@ -3152,7 +3152,7 @@ pub(super) mod types {
Ok(())
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
@@ -3201,7 +3201,7 @@ pub(super) mod types {
impl Initializer for PyUnicodeEncodeError {
type Args = FuncArgs;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
parse_tuple_arity(&args, 5, vm)?;
type Args = (PyStrRef, PyStrRef, isize, isize, PyStrRef);
let (encoding, object, start, end, reason): Args = args.bind(vm)?;
@@ -3215,7 +3215,7 @@ pub(super) mod types {
Ok(())
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
@@ -3263,7 +3263,7 @@ pub(super) mod types {
impl Initializer for PyUnicodeTranslateError {
type Args = FuncArgs;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
parse_tuple_arity(&args, 4, vm)?;
type Args = (PyStrRef, isize, isize, PyStrRef);
let (object, start, end, reason): Args = args.bind(vm)?;
@@ -3276,7 +3276,7 @@ pub(super) mod types {
Ok(())
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
+12 -13
View File
@@ -2437,14 +2437,14 @@ impl FrameObject {
/// `proxy.setdefault(key, default)`.
pub(crate) fn framelocalsproxy_setdefault(
&self,
key: PyObjectRef,
key: &PyObject,
default: PyObjectRef,
vm: &VirtualMachine,
) -> PyResult {
match self.framelocalsproxy_getitem(key.clone(), vm) {
match self.framelocalsproxy_getitem(key.to_owned(), 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),
@@ -3982,7 +3982,7 @@ impl ExecutingFrame<'_> {
let close_result = if let Some(coro) = self.builtin_coro(jen) {
coro.close(jen, vm).map(|_| ())
} else {
match vm.get_attribute_opt(jen.to_owned(), "close") {
match vm.get_attribute_opt(jen, "close") {
Ok(Some(close_meth)) => close_meth.call((), vm).map(|_| ()),
Ok(None) => Ok(()),
Err(e) => {
@@ -4028,8 +4028,7 @@ impl ExecutingFrame<'_> {
let thrower = if let Some(coro) = self.builtin_coro(jen) {
Some(Either::A(coro))
} else {
vm.get_attribute_opt(jen.to_owned(), "throw")?
.map(Either::B)
vm.get_attribute_opt(jen, "throw")?.map(Either::B)
};
if let Some(thrower) = thrower {
let ret = match thrower {
@@ -5219,7 +5218,7 @@ impl ExecutingFrame<'_> {
if nargs_val > 0 {
// Get __match_args__ from the class
let match_args =
vm.get_attribute_opt(cls.clone(), identifier!(vm, __match_args__))?;
vm.get_attribute_opt(&cls, identifier!(vm, __match_args__))?;
if let Some(match_args) = match_args {
// Convert to tuple
@@ -7459,13 +7458,13 @@ impl ExecutingFrame<'_> {
let obj_arg = if self_obj.is(start_type.as_object()) {
None
} else {
Some(self_obj.to_owned())
Some(self_obj)
};
let result = vm
.call_get_descriptor_specific(
&descr,
obj_arg,
Some(start_type.as_object().to_owned()),
Some(start_type.as_object()),
)
.unwrap_or(Ok(descr))?;
found = Some(result);
@@ -7521,9 +7520,9 @@ impl ExecutingFrame<'_> {
} else if let Some(descr_get) = descr_cls.slots.descr_get.load() {
// Has __get__ but not METHOD_DESCRIPTOR: bind it
let bound = descr_get(
descr,
Some(self_val.clone()),
Some(start_type.as_object().to_owned()),
&descr,
Some(&self_val),
Some(start_type.as_object()),
vm,
)?;
found = Some((bound, false));
@@ -8445,7 +8444,7 @@ impl ExecutingFrame<'_> {
let name = self.code.names[idx as usize];
// Load attribute, and transform any error into import error.
if let Some(obj) = vm.get_attribute_opt(module.to_owned(), name)? {
if let Some(obj) = vm.get_attribute_opt(module, name)? {
return Ok(obj);
}
// fallback to importing '{module.__name__}.{name}' from sys.modules
+7 -8
View File
@@ -164,8 +164,8 @@ pub fn import_source(vm: &VirtualMachine, module_name: &str, content: &str) -> P
/// import path below and by [`crate::VirtualMachine::import`]'s
/// `sys.modules`-cache fast path).
pub(crate) fn is_module_initializing(module: &PyObject, vm: &VirtualMachine) -> PyResult<bool> {
match vm.get_attribute_opt(module.to_owned(), vm.ctx.intern_str("__spec__"))? {
Some(spec) => match vm.get_attribute_opt(spec, vm.ctx.intern_str("_initializing"))? {
match vm.get_attribute_opt(module, vm.ctx.intern_str("__spec__"))? {
Some(spec) => match vm.get_attribute_opt(&spec, vm.ctx.intern_str("_initializing"))? {
Some(v) => v.try_to_bool(vm),
None => Ok(false),
},
@@ -383,7 +383,7 @@ pub(crate) fn is_stdlib_module_name(name: &PyObject, vm: &VirtualMachine) -> PyR
/// PyImport_ImportModuleLevelObject
pub(crate) fn import_module_level(
name: &Py<PyStr>,
globals: Option<PyObjectRef>,
globals: Option<&PyObject>,
fromlist: Option<PyObjectRef>,
level: i32,
vm: &VirtualMachine,
@@ -411,12 +411,11 @@ pub(crate) fn import_module_level(
let abs_name = if level > 0 {
// When globals is not provided (Rust None), raise KeyError
// matching resolve_name() where globals==NULL
if globals.is_none() {
let Some(globals_ref) = globals else {
return Err(vm.new_key_error(vm.ctx.new_str("'__name__' not in globals").into()));
}
let globals_ref = globals.as_ref().unwrap();
};
// When globals is Python None, treat like empty mapping
let empty_dict_obj;
let empty_dict_obj: PyObjectRef;
let globals_ref = if vm.is_none(globals_ref) {
empty_dict_obj = vm.ctx.new_dict().into();
&empty_dict_obj
@@ -464,7 +463,7 @@ pub(crate) fn import_module_level(
// crash inside _handle_fromlist; IMPORT_FROM handles per-attribute
// errors with proper ImportError conversion.
let has_path = vm
.get_attribute_opt(module.clone(), vm.ctx.intern_str("__path__"))?
.get_attribute_opt(&module, vm.ctx.intern_str("__path__"))?
.is_some();
if has_path {
let handle_fromlist = vm.importlib.get_attr("_handle_fromlist", vm)?;
+8 -13
View File
@@ -263,8 +263,8 @@ impl PyObject {
if let Some(descr_get) = descr_get
&& descr_cls.slots.descr_set.load().is_some()
{
let cls = obj_cls.to_owned().into();
return descr_get(descr, Some(self.to_owned()), Some(cls), vm).map(Some);
return descr_get(descr.as_object(), Some(self), Some(obj_cls.as_object()), vm)
.map(Some);
}
Some((descr, descr_get))
}
@@ -286,8 +286,7 @@ impl PyObject {
} else if let Some((attr, descr_get)) = cls_attr {
match descr_get {
Some(descr_get) => {
let cls = obj_cls.to_owned().into();
descr_get(attr, Some(self.to_owned()), Some(cls), vm).map(Some)
descr_get(attr.as_object(), Some(self), Some(obj_cls.as_object()), vm).map(Some)
}
None => Ok(Some(attr)),
}
@@ -497,7 +496,7 @@ impl PyObject {
/// Other exceptions are propagated.
fn abstract_get_bases(&self, vm: &VirtualMachine) -> PyResult<Option<PyTupleRef>> {
Ok(vm
.get_attribute_opt(self.to_owned(), identifier!(vm, __bases__))?
.get_attribute_opt(self, identifier!(vm, __bases__))?
// If we get `None` then AttributeError was masked.
.and_then(|bases| {
// Check if it's a tuple
@@ -641,8 +640,7 @@ impl PyObject {
// PyType_Check(cls) - cls is a type object
let mut retval = self.class().is_subtype(cls);
if !retval
&& let Some(i_cls) =
vm.get_attribute_opt(self.to_owned(), identifier!(vm, __class__))?
&& let Some(i_cls) = vm.get_attribute_opt(self, identifier!(vm, __class__))?
&& let Ok(i_cls_type) = PyTypeRef::try_from_object(vm, i_cls)
&& !i_cls_type.is(self.class())
{
@@ -656,9 +654,7 @@ impl PyObject {
"isinstance() arg 2 must be a type, a tuple of types, or a union",
)?;
if let Some(i_cls) =
vm.get_attribute_opt(self.to_owned(), identifier!(vm, __class__))?
{
if let Some(i_cls) = vm.get_attribute_opt(self, identifier!(vm, __class__))? {
i_cls.abstract_issubclass(cls, vm)
} else {
Ok(false)
@@ -776,7 +772,7 @@ impl PyObject {
}
if let Some(class_getitem) =
vm.get_attribute_opt(self.to_owned(), identifier!(vm, __class_getitem__))?
vm.get_attribute_opt(self, identifier!(vm, __class_getitem__))?
&& !vm.is_none(&class_getitem)
{
return class_getitem.call((needle,), vm);
@@ -864,8 +860,7 @@ impl PyObject {
let descr_get = res.class().slots.descr_get.load();
if let Some(descr_get) = descr_get {
let obj_cls = obj_cls.to_owned().into();
descr_get(res, Some(self.to_owned()), Some(obj_cls), vm).map(Some)
descr_get(res.as_object(), Some(self), Some(obj_cls.as_object()), vm).map(Some)
} else {
Ok(Some(res))
}
+1 -1
View File
@@ -180,7 +180,7 @@ mod _abc {
while let PyIterReturn::Return(key) = iter.next(vm)? {
// Try to get the attribute from cls - key should be a string
if let Some(key_str) = key.downcast_ref::<PyStr>()
&& let Some(value) = vm.get_attribute_opt(cls.to_owned(), key_str)?
&& let Some(value) = vm.get_attribute_opt(cls, key_str)?
&& let Ok(is_abstract) = value.get_attr("__isabstractmethod__", vm)
&& is_abstract.try_to_bool(vm)?
{
+20 -20
View File
@@ -81,7 +81,7 @@ fn is_ast_instance(vm: &VirtualMachine, object: &PyObject) -> PyResult<bool> {
}
fn get_node_field(vm: &VirtualMachine, obj: &PyObject, field: &'static str, typ: &str) -> PyResult {
vm.get_attribute_opt(obj.to_owned(), field)?
vm.get_attribute_opt(obj, field)?
.ok_or_else(|| vm.new_type_error(format!(r#"required field "{field}" missing from {typ}"#)))
}
@@ -134,7 +134,7 @@ fn get_node_field_opt(
field: &'static str,
) -> PyResult<Option<PyObjectRef>> {
Ok(vm
.get_attribute_opt(obj.to_owned(), field)?
.get_attribute_opt(obj, field)?
.filter(|obj| !vm.is_none(obj)))
}
@@ -156,7 +156,7 @@ fn get_node_list_field_object(
field: &'static str,
typ: &str,
) -> PyResult<PyObjectRef> {
let Some(value) = vm.get_attribute_opt(obj.to_owned(), field)? else {
let Some(value) = vm.get_attribute_opt(obj, field)? else {
return Ok(vm.ctx.new_list(Vec::new()).into());
};
value.downcast_ref::<PyList>().ok_or_else(|| {
@@ -422,7 +422,7 @@ fn get_attribute_from_field(
let field = field
.downcast::<PyStr>()
.map_err(|_| vm.new_type_error("attribute name must be string"))?;
vm.get_attribute_opt(obj.to_owned(), &field)
vm.get_attribute_opt(obj, &field)
}
#[derive(Default)]
@@ -527,7 +527,7 @@ fn copy_ast_passthrough_fields(
};
for field in fields {
if let Some(value) = vm.get_attribute_opt(source.to_owned(), *field)? {
if let Some(value) = vm.get_attribute_opt(source, *field)? {
target.set_attr(*field, value, vm)?;
}
}
@@ -569,7 +569,7 @@ fn get_ast_location_field(
field: &'static str,
) -> PyResult<Option<PyObjectRef>> {
Ok(vm
.get_attribute_opt(object.to_owned(), field)?
.get_attribute_opt(object, field)?
.filter(|value| !vm.is_none(value)))
}
@@ -705,50 +705,50 @@ fn synthetic_source_from_ast_object(vm: &VirtualMachine, object: &PyObject) -> P
fn range_from_object(
vm: &VirtualMachine,
source_file: &SourceFile,
object: PyObjectRef,
object: &PyObject,
name: &str,
) -> PyResult<TextRange> {
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(
vm: &VirtualMachine,
source_file: &SourceFile,
object: PyObjectRef,
object: &PyObject,
) -> PyResult<TextRange> {
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(
vm: &VirtualMachine,
source_file: &SourceFile,
object: PyObjectRef,
object: &PyObject,
) -> PyResult<TextRange> {
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(
vm: &VirtualMachine,
source_file: &SourceFile,
object: PyObjectRef,
object: &PyObject,
) -> PyResult<TextRange> {
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(
vm: &VirtualMachine,
source_file: &SourceFile,
object: PyObjectRef,
object: &PyObject,
) -> PyResult<TextRange> {
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(
vm: &VirtualMachine,
source_file: &SourceFile,
object: PyObjectRef,
object: &PyObject,
) -> PyResult<TextRange> {
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(
@@ -1562,7 +1562,7 @@ fn node_list_field(
object: &PyObject,
field: &'static str,
) -> Vec<PyObjectRef> {
vm.get_attribute_opt(object.to_owned(), field)
vm.get_attribute_opt(object, field)
.ok()
.flatten()
.and_then(|value| {
@@ -1578,7 +1578,7 @@ fn node_optional_field(
object: &PyObject,
field: &'static str,
) -> Option<PyObjectRef> {
vm.get_attribute_opt(object.to_owned(), field)
vm.get_attribute_opt(object, field)
.ok()
.flatten()
.filter(|value| !vm.is_none(value))
+7 -7
View File
@@ -137,9 +137,9 @@ pub(super) fn invalid_constant_type(expr: &ast::Expr) -> Option<Box<str>> {
pub(super) fn runtime_string_from_pyobject(
vm: &VirtualMachine,
object: PyObjectRef,
object: &PyObject,
) -> (Option<Box<str>>, Option<Vec<u8>>) {
runtime_string_from_object(vm, &object)
runtime_string_from_object(vm, object)
}
pub(super) fn runtime_string_object(
@@ -367,7 +367,7 @@ fn first_invalid_constant_type(vm: &VirtualMachine, value_object: &PyObject) ->
))
})?;
for item in tuple.iter() {
if let Some(invalid_type) = first_invalid_constant_type_opt(vm, item.clone())? {
if let Some(invalid_type) = first_invalid_constant_type_opt(vm, item)? {
return Ok(invalid_type);
}
}
@@ -377,7 +377,7 @@ fn first_invalid_constant_type(vm: &VirtualMachine, value_object: &PyObject) ->
vm.with_recursion(" during compilation", || {
let set = value_object.to_owned().downcast::<PyFrozenSet>().unwrap();
for item in set.elements() {
if let Some(invalid_type) = first_invalid_constant_type_opt(vm, item)? {
if let Some(invalid_type) = first_invalid_constant_type_opt(vm, &item)? {
return Ok(invalid_type);
}
}
@@ -390,7 +390,7 @@ fn first_invalid_constant_type(vm: &VirtualMachine, value_object: &PyObject) ->
fn first_invalid_constant_type_opt(
vm: &VirtualMachine,
value_object: PyObjectRef,
value_object: &PyObject,
) -> PyResult<Option<String>> {
let cls = value_object.class();
if cls.is(vm.ctx.types.none_type)
@@ -405,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()))
}
@@ -499,7 +499,7 @@ impl Node for Constant {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Constant")?;
let range = range_from_object(vm, source_file, &object, "Constant")?;
constant_from_object_with_range(vm, source_file, &object, range)
}
}
+6 -6
View File
@@ -30,7 +30,7 @@ impl Node for ast::ExceptHandler {
object: PyObjectRef,
) -> PyResult<Self> {
ensure_excepthandler_node(vm, &object)?;
let range = excepthandler_range_from_object(vm, source_file, object.clone())?;
let range = excepthandler_range_from_object(vm, source_file, &object)?;
Ok(Self::ExceptHandler(except_handler_from_object_with_range(
vm,
source_file,
@@ -67,12 +67,12 @@ fn except_handler_from_object_with_range(
pub(super) fn except_handler_from_object_unvalidated_range(
vm: &VirtualMachine,
source_file: &SourceFile,
object: PyObjectRef,
object: &PyObject,
) -> PyResult<ast::ExceptHandler> {
ensure_excepthandler_node(vm, &object)?;
let range = excepthandler_range_from_object_unvalidated(vm, source_file, &object)?;
ensure_excepthandler_node(vm, object)?;
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)?,
))
}
@@ -111,7 +111,7 @@ impl Node for ast::ExceptHandlerExceptHandler {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "ExceptHandler")?;
let range = range_from_object(vm, source_file, &object, "ExceptHandler")?;
except_handler_from_object_with_range(vm, source_file, &object, range)
}
}
+25 -25
View File
@@ -158,7 +158,7 @@ impl Node for ast::Expr {
object.repr(vm)?
)));
};
let range = expr_range_from_object(vm, source_file, object.clone())?;
let range = expr_range_from_object(vm, source_file, &object)?;
Ok(match kind {
ExprKind::BoolOp => Self::BoolOp(expr_bool_op_from_object_with_range(
vm,
@@ -391,7 +391,7 @@ impl Node for ast::ExprBoolOp {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "BoolOp")?;
let range = range_from_object(vm, source_file, &object, "BoolOp")?;
expr_bool_op_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -436,7 +436,7 @@ impl Node for ast::ExprNamed {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "NamedExpr")?;
let range = range_from_object(vm, source_file, &object, "NamedExpr")?;
expr_named_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -489,7 +489,7 @@ impl Node for ast::ExprBinOp {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "BinOp")?;
let range = range_from_object(vm, source_file, &object, "BinOp")?;
expr_bin_op_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -537,7 +537,7 @@ impl Node for ast::ExprUnaryOp {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "UnaryOp")?;
let range = range_from_object(vm, source_file, &object, "UnaryOp")?;
expr_unary_op_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -589,7 +589,7 @@ impl Node for ast::ExprLambda {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Lambda")?;
let range = range_from_object(vm, source_file, &object, "Lambda")?;
expr_lambda_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -638,7 +638,7 @@ impl Node for ast::ExprIf {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "IfExp")?;
let range = range_from_object(vm, source_file, &object, "IfExp")?;
expr_if_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -707,7 +707,7 @@ impl Node for ast::ExprDict {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Dict")?;
let range = range_from_object(vm, source_file, &object, "Dict")?;
expr_dict_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -754,7 +754,7 @@ impl Node for ast::ExprSet {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Set")?;
let range = range_from_object(vm, source_file, &object, "Set")?;
expr_set_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -799,7 +799,7 @@ impl Node for ast::ExprListComp {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "ListComp")?;
let range = range_from_object(vm, source_file, &object, "ListComp")?;
expr_list_comp_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -844,7 +844,7 @@ impl Node for ast::ExprSetComp {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "SetComp")?;
let range = range_from_object(vm, source_file, &object, "SetComp")?;
expr_set_comp_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -899,7 +899,7 @@ impl Node for ast::ExprDictComp {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "DictComp")?;
let range = range_from_object(vm, source_file, &object, "DictComp")?;
expr_dict_comp_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -946,7 +946,7 @@ impl Node for ast::ExprGenerator {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "GeneratorExp")?;
let range = range_from_object(vm, source_file, &object, "GeneratorExp")?;
expr_generator_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -986,7 +986,7 @@ impl Node for ast::ExprAwait {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Await")?;
let range = range_from_object(vm, source_file, &object, "Await")?;
expr_await_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1029,7 +1029,7 @@ impl Node for ast::ExprYield {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Yield")?;
let range = range_from_object(vm, source_file, &object, "Yield")?;
expr_yield_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1070,7 +1070,7 @@ impl Node for ast::ExprYieldFrom {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "YieldFrom")?;
let range = range_from_object(vm, source_file, &object, "YieldFrom")?;
expr_yield_from_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1127,7 +1127,7 @@ impl Node for ast::ExprCompare {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Compare")?;
let range = range_from_object(vm, source_file, &object, "Compare")?;
expr_compare_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1189,7 +1189,7 @@ impl Node for ast::ExprCall {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Call")?;
let range = range_from_object(vm, source_file, &object, "Call")?;
expr_call_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1242,7 +1242,7 @@ impl Node for ast::ExprAttribute {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Attribute")?;
let range = range_from_object(vm, source_file, &object, "Attribute")?;
expr_attribute_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1294,7 +1294,7 @@ impl Node for ast::ExprSubscript {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Subscript")?;
let range = range_from_object(vm, source_file, &object, "Subscript")?;
expr_subscript_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1342,7 +1342,7 @@ impl Node for ast::ExprStarred {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Starred")?;
let range = range_from_object(vm, source_file, &object, "Starred")?;
expr_starred_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1391,7 +1391,7 @@ impl Node for ast::ExprName {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Name")?;
let range = range_from_object(vm, source_file, &object, "Name")?;
expr_name_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1448,7 +1448,7 @@ impl Node for ast::ExprList {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "List")?;
let range = range_from_object(vm, source_file, &object, "List")?;
expr_list_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1507,7 +1507,7 @@ impl Node for ast::ExprTuple {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Tuple")?;
let range = range_from_object(vm, source_file, &object, "Tuple")?;
expr_tuple_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1562,7 +1562,7 @@ impl Node for ast::ExprSlice {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Slice")?;
let range = range_from_object(vm, source_file, &object, "Slice")?;
expr_slice_from_object_with_range(vm, source_file, &object, range)
}
}
+1 -1
View File
@@ -94,7 +94,7 @@ impl Node for ast::Alias {
asname: get_node_field_opt(vm, &object, "asname")?
.map(|obj| Node::ast_from_object(vm, source_file, obj))
.transpose()?,
range: range_from_object(vm, source_file, object, "alias")?,
range: range_from_object(vm, source_file, &object, "alias")?,
})
}
}
+3 -3
View File
@@ -196,9 +196,9 @@ impl Node for ast::Parameter {
let type_comment = get_ast_string_field_opt(vm, &_object, "type_comment")?;
let (runtime_type_comment, runtime_type_comment_bytes) = type_comment
.map_or((None, None), |type_comment| {
super::constant::runtime_string_from_pyobject(vm, type_comment)
super::constant::runtime_string_from_pyobject(vm, &type_comment)
});
let range = range_from_object(vm, source_file, _object, "arg")?;
let range = range_from_object(vm, source_file, &_object, "arg")?;
Ok(Self {
node_index: Default::default(),
name,
@@ -241,7 +241,7 @@ impl Node for ast::Keyword {
.map(|obj| Node::ast_from_object(vm, source_file, obj))
.transpose()?,
value: get_required_node_field(vm, source_file, &_object, "value", "keyword")?,
range: range_from_object(vm, source_file, _object, "keyword")?,
range: range_from_object(vm, source_file, &_object, "keyword")?,
})
}
}
+9 -9
View File
@@ -106,7 +106,7 @@ impl Node for ast::Pattern {
object.repr(vm)?
)));
};
let range = pattern_range_from_object(vm, source_file, object.clone())?;
let range = pattern_range_from_object(vm, source_file, &object)?;
Ok(match kind {
PatternKind::Value => Self::MatchValue(pattern_match_value_from_object_with_range(
vm,
@@ -236,7 +236,7 @@ impl Node for ast::PatternMatchValue {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "MatchValue")?;
let range = range_from_object(vm, source_file, &object, "MatchValue")?;
pattern_match_value_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -284,7 +284,7 @@ impl Node for ast::PatternMatchSingleton {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "MatchSingleton")?;
let range = range_from_object(vm, source_file, &object, "MatchSingleton")?;
pattern_match_singleton_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -361,7 +361,7 @@ impl Node for ast::PatternMatchSequence {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "MatchSequence")?;
let range = range_from_object(vm, source_file, &object, "MatchSequence")?;
pattern_match_sequence_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -431,7 +431,7 @@ impl Node for ast::PatternMatchMapping {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "MatchMapping")?;
let range = range_from_object(vm, source_file, &object, "MatchMapping")?;
pattern_match_mapping_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -528,7 +528,7 @@ impl Node for ast::PatternMatchClass {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "MatchClass")?;
let range = range_from_object(vm, source_file, &object, "MatchClass")?;
pattern_match_class_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -636,7 +636,7 @@ impl Node for ast::PatternMatchStar {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "MatchStar")?;
let range = range_from_object(vm, source_file, &object, "MatchStar")?;
pattern_match_star_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -685,7 +685,7 @@ impl Node for ast::PatternMatchAs {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "MatchAs")?;
let range = range_from_object(vm, source_file, &object, "MatchAs")?;
pattern_match_as_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -732,7 +732,7 @@ impl Node for ast::PatternMatchOr {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "MatchOr")?;
let range = range_from_object(vm, source_file, &object, "MatchOr")?;
pattern_match_or_from_object_with_range(vm, source_file, &object, range)
}
}
+6 -6
View File
@@ -362,7 +362,7 @@ pub(crate) mod _ast {
// type.__call__ does not invoke slot_init after slot_new
// for types with a custom slot_new, so we must call it here.
Self::slot_init(zelf.clone(), args, vm)?;
Self::slot_init(&zelf, args, vm)?;
Ok(zelf)
}
@@ -375,7 +375,7 @@ pub(crate) mod _ast {
impl Initializer for NodeAst {
type Args = FuncArgs;
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let fields = zelf
.class()
.get_attr(vm.ctx.intern_str("_fields"))
@@ -409,7 +409,7 @@ pub(crate) mod _ast {
for (i, arg) in args.args.into_iter().enumerate() {
let name = fields_seq.get_item(i as isize, vm)?;
ast_set_attr(&zelf, &name, arg, vm)?;
ast_set_attr(zelf, &name, arg, vm)?;
ast_replace_set_discard(&remaining_fields, &name, vm)?;
}
for (key, value) in args.kwargs {
@@ -475,7 +475,7 @@ Support for arbitrary keyword arguments is deprecated and will be removed in Pyt
} else if ftype.fast_isinstance(vm.ctx.types.generic_alias_type) {
// List field (list[T]) — default to []
let empty_list: PyObjectRef = vm.ctx.new_list(vec![]).into();
ast_set_attr(&zelf, &field, empty_list, vm)?;
ast_set_attr(zelf, &field, empty_list, vm)?;
} else if ftype.is(&expr_ctx_type) {
// expr_context — default to Load()
let load_type =
@@ -485,7 +485,7 @@ Support for arbitrary keyword arguments is deprecated and will be removed in Pyt
.unwrap_or_else(|| {
vm.ctx.new_base_object(load_type, Some(vm.ctx.new_dict()))
});
ast_set_attr(&zelf, &field, load_instance, vm)?;
ast_set_attr(zelf, &field, load_instance, vm)?;
} else {
// Required field missing: emit DeprecationWarning.
let field_repr = field.repr(vm)?;
@@ -525,7 +525,7 @@ This will become an error in Python 3.15.",
Ok(())
}
fn init(_zelf: PyRef<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
fn init(_zelf: &Py<Self>, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> {
unreachable!("slot_init is defined")
}
}
+27 -27
View File
@@ -49,7 +49,7 @@ fn runtime_stmt_type_comment(
type_comment: Option<PyObjectRef>,
) -> (Option<Box<str>>, Option<Vec<u8>>) {
type_comment.map_or((None, None), |type_comment| {
super::constant::runtime_string_from_pyobject(vm, type_comment)
super::constant::runtime_string_from_pyobject(vm, &type_comment)
})
}
@@ -192,7 +192,7 @@ impl Node for ast::Stmt {
object.repr(vm)?
)));
};
let range = stmt_range_from_object(vm, source_file, object.clone())?;
let range = stmt_range_from_object(vm, source_file, &object)?;
Ok(match kind {
StmtKind::FunctionDef { is_async } => {
Self::FunctionDef(stmt_function_def_from_object_with_range(
@@ -466,7 +466,7 @@ impl Node for ast::StmtFunctionDef {
} else {
"FunctionDef"
};
let range = range_from_object(vm, source_file, _object.clone(), typ)?;
let range = range_from_object(vm, source_file, &_object, typ)?;
stmt_function_def_from_object_with_range(vm, source_file, &_object, range, is_async)
}
}
@@ -576,7 +576,7 @@ impl Node for ast::StmtClassDef {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "ClassDef")?;
let range = range_from_object(vm, source_file, &_object, "ClassDef")?;
stmt_class_def_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -617,7 +617,7 @@ impl Node for ast::StmtReturn {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "Return")?;
let range = range_from_object(vm, source_file, &_object, "Return")?;
stmt_return_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -664,7 +664,7 @@ impl Node for ast::StmtDelete {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "Delete")?;
let range = range_from_object(vm, source_file, &_object, "Delete")?;
stmt_delete_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -729,7 +729,7 @@ impl Node for ast::StmtAssign {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Assign")?;
let range = range_from_object(vm, source_file, &object, "Assign")?;
stmt_assign_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -785,7 +785,7 @@ impl Node for ast::StmtTypeAlias {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "TypeAlias")?;
let range = range_from_object(vm, source_file, &_object, "TypeAlias")?;
stmt_type_alias_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -837,7 +837,7 @@ impl Node for ast::StmtAugAssign {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "AugAssign")?;
let range = range_from_object(vm, source_file, &_object, "AugAssign")?;
stmt_aug_assign_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -903,7 +903,7 @@ impl Node for ast::StmtAnnAssign {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "AnnAssign")?;
let range = range_from_object(vm, source_file, &_object, "AnnAssign")?;
stmt_ann_assign_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -1002,7 +1002,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)?;
let range = range_from_object(vm, source_file, &_object, typ)?;
stmt_for_from_object_with_range(vm, source_file, &_object, range, is_async)
}
}
@@ -1067,7 +1067,7 @@ impl Node for ast::StmtWhile {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "While")?;
let range = range_from_object(vm, source_file, &_object, "While")?;
stmt_while_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -1101,7 +1101,7 @@ impl Node for ast::StmtIf {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "If")?;
let range = range_from_object(vm, source_file, &object, "If")?;
elif_else_clause::ast_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1179,7 +1179,7 @@ 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)?;
let range = range_from_object(vm, source_file, &_object, typ)?;
stmt_with_from_object_with_range(vm, source_file, &_object, range, is_async)
}
}
@@ -1222,7 +1222,7 @@ impl Node for ast::StmtMatch {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "Match")?;
let range = range_from_object(vm, source_file, &_object, "Match")?;
stmt_match_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -1269,7 +1269,7 @@ impl Node for ast::StmtRaise {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "Raise")?;
let range = range_from_object(vm, source_file, &_object, "Raise")?;
stmt_raise_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -1337,7 +1337,7 @@ fn except_handler_list_from_field(
} else {
Some(vm.with_recursion(&recursion_context, || {
if is_try_star {
except_handler_from_object_unvalidated_range(vm, source_file, item)
except_handler_from_object_unvalidated_range(vm, source_file, &item)
} else {
Node::ast_from_object(vm, source_file, item)
}
@@ -1423,7 +1423,7 @@ impl Node for ast::StmtTry {
|| is_node_instance(vm, &_object, pyast::NodeStmtTryStar::static_type())?
);
let typ = if is_star { "TryStar" } else { "Try" };
let range = range_from_object(vm, source_file, _object.clone(), typ)?;
let range = range_from_object(vm, source_file, &_object, typ)?;
stmt_try_from_object_with_range(vm, source_file, &_object, range, is_star)
}
}
@@ -1469,7 +1469,7 @@ impl Node for ast::StmtAssert {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "Assert")?;
let range = range_from_object(vm, source_file, &_object, "Assert")?;
stmt_assert_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -1511,7 +1511,7 @@ impl Node for ast::StmtImport {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "Import")?;
let range = range_from_object(vm, source_file, &_object, "Import")?;
stmt_import_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -1586,7 +1586,7 @@ impl Node for ast::StmtImportFrom {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "ImportFrom")?;
let range = range_from_object(vm, source_file, &_object, "ImportFrom")?;
stmt_import_from_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -1625,7 +1625,7 @@ impl Node for ast::StmtGlobal {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "Global")?;
let range = range_from_object(vm, source_file, &_object, "Global")?;
stmt_global_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -1664,7 +1664,7 @@ impl Node for ast::StmtNonlocal {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "Nonlocal")?;
let range = range_from_object(vm, source_file, &_object, "Nonlocal")?;
stmt_nonlocal_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -1703,7 +1703,7 @@ impl Node for ast::StmtExpr {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object.clone(), "Expr")?;
let range = range_from_object(vm, source_file, &_object, "Expr")?;
stmt_expr_from_object_with_range(vm, source_file, &_object, range)
}
}
@@ -1755,7 +1755,7 @@ impl Node for ast::StmtPass {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object, "Pass")?;
let range = range_from_object(vm, source_file, &_object, "Pass")?;
Ok(stmt_pass_from_object_with_range(range))
}
}
@@ -1786,7 +1786,7 @@ impl Node for ast::StmtBreak {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object, "Break")?;
let range = range_from_object(vm, source_file, &_object, "Break")?;
Ok(stmt_break_from_object_with_range(range))
}
}
@@ -1817,7 +1817,7 @@ impl Node for ast::StmtContinue {
source_file: &SourceFile,
_object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, _object, "Continue")?;
let range = range_from_object(vm, source_file, &_object, "Continue")?;
Ok(stmt_continue_from_object_with_range(range))
}
}
+4 -4
View File
@@ -571,7 +571,7 @@ impl Node for JoinedStr {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "JoinedStr")?;
let range = range_from_object(vm, source_file, &object, "JoinedStr")?;
joined_str_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -670,7 +670,7 @@ impl Node for FormattedValue {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "FormattedValue")?;
let range = range_from_object(vm, source_file, &object, "FormattedValue")?;
formatted_value_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1081,7 +1081,7 @@ impl Node for TemplateStr {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "TemplateStr")?;
let range = range_from_object(vm, source_file, &object, "TemplateStr")?;
template_str_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -1188,7 +1188,7 @@ impl Node for TStringInterpolation {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = range_from_object(vm, source_file, object.clone(), "Interpolation")?;
let range = range_from_object(vm, source_file, &object, "Interpolation")?;
tstring_interpolation_from_object_with_range(vm, source_file, &object, range)
}
}
+4 -4
View File
@@ -97,7 +97,7 @@ impl Node for ast::TypeParam {
object.repr(vm)?
)));
};
let range = type_param_range_from_object(vm, source_file, object.clone())?;
let range = type_param_range_from_object(vm, source_file, &object)?;
Ok(match kind {
TypeParamKind::TypeVar => Self::TypeVar(type_var_from_object_with_range(
vm,
@@ -166,7 +166,7 @@ impl Node for ast::TypeParamTypeVar {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = type_param_range_from_object(vm, source_file, object.clone())?;
let range = type_param_range_from_object(vm, source_file, &object)?;
type_var_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -213,7 +213,7 @@ impl Node for ast::TypeParamParamSpec {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = type_param_range_from_object(vm, source_file, object.clone())?;
let range = type_param_range_from_object(vm, source_file, &object)?;
param_spec_from_object_with_range(vm, source_file, &object, range)
}
}
@@ -263,7 +263,7 @@ impl Node for ast::TypeParamTypeVarTuple {
source_file: &SourceFile,
object: PyObjectRef,
) -> PyResult<Self> {
let range = type_param_range_from_object(vm, source_file, object.clone())?;
let range = type_param_range_from_object(vm, source_file, &object)?;
type_var_tuple_from_object_with_range(vm, source_file, &object, range)
}
}
+1 -1
View File
@@ -27,7 +27,7 @@ mod _codecs {
#[pyfunction]
fn unregister(search_function: PyObjectRef, vm: &VirtualMachine) {
vm.state.codec_registry.unregister(search_function);
vm.state.codec_registry.unregister(&search_function);
}
#[pyfunction]
+2 -2
View File
@@ -460,7 +460,7 @@ mod _collections {
type Args = PyDequeOptions;
fn init(
zelf: PyRef<Self>,
zelf: &Py<Self>,
PyDequeOptions { iterable, maxlen }: Self::Args,
vm: &VirtualMachine,
) -> PyResult<()> {
@@ -1002,7 +1002,7 @@ mod _collections {
impl Initializer for PyDefaultDict {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, mut args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, mut args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let default_factory = args.take_positional().map_or(Ok(None), |factory| {
let is_none = factory.is(&vm.ctx.none());
@@ -602,14 +602,14 @@ pub(crate) mod ordered_dict {
impl Initializer for PyOrderedDict {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
if args.args.len() > 1 {
return Err(vm.new_type_error(format!(
"OrderedDict expected at most 1 argument, got {}",
args.args.len()
)));
}
Self::update(zelf, args, vm)
Self::update(zelf.to_owned(), args, vm)
}
}
+4 -3
View File
@@ -266,13 +266,14 @@ pub(crate) mod _ctypes {
#[cfg(target_os = "windows")]
#[pyattr(name = "COMError", once)]
fn com_error(vm: &VirtualMachine) -> PyTypeRef {
use crate::PyObject;
use crate::builtins::type_::PyAttributes;
use crate::function::FuncArgs;
use crate::types::{PyTypeFlags, PyTypeSlots};
// Sets hresult, text, details as instance attributes in __init__
// This function has InitFunc signature for direct slots.init use
fn comerror_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn comerror_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let (hresult, text, details): (
Option<PyObjectRef>,
Option<PyObjectRef>,
@@ -831,13 +832,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, obj.clone(), typ, vm)
super::function::cast_impl(&obj, obj.clone(), &typ, vm)
}
/// Return buffer interface information for a ctypes type or object.
+4 -4
View File
@@ -3,7 +3,7 @@ use super::base::{CDATA_BUFFER_METHODS, PyCData};
use crate::common::lock::LazyLock;
use crate::sliceable::SaturatedSliceIter;
use crate::{
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine,
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine,
atomic_func,
builtins::{
PyBytes, PyInt, PyList, PySlice, PyStr, PyType, PyTypeRef, genericalias::PyGenericAlias,
@@ -175,7 +175,7 @@ pub(super) struct PyCArrayType(PyType);
impl Initializer for PyCArrayType {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// zelf is the newly created array type (e.g., T in "class T(Array)")
let new_type: &PyType = &zelf.0;
@@ -450,10 +450,10 @@ impl Constructor for PyCArray {
impl Initializer for PyCArray {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, 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, vm)?;
Self::setitem_by_index(zelf, i as isize, value, vm)?;
}
Ok(())
}
+5 -4
View File
@@ -1452,18 +1452,19 @@ impl Representable for PyCField {
/// PyCField_get
impl GetDescriptor for PyCField {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
_cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
_cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
let zelf = zelf
.to_owned()
.downcast::<Self>()
.map_err(|_| vm.new_type_error("expected CField"))?;
// If obj is None, return the descriptor itself (class attribute access)
let obj = match obj {
Some(obj) if !vm.is_none(&obj) => obj,
Some(obj) if !vm.is_none(obj) => obj.to_owned(),
_ => return Ok(zelf.into()),
};
+11 -11
View File
@@ -311,8 +311,8 @@ pub(super) struct PyCFuncPtrType(PyType);
impl Initializer for PyCFuncPtrType {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let obj: PyObjectRef = zelf.into();
fn init(zelf: &Py<Self>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let obj: PyObjectRef = zelf.to_owned().into();
let new_type: PyTypeRef = obj
.downcast()
.map_err(|_| vm.new_type_error("expected type"))?;
@@ -532,11 +532,11 @@ fn cast_check_pointertype(ctype: &PyObject, vm: &VirtualMachine) -> bool {
pub(super) fn cast_impl(
obj: &PyObject,
src: PyObjectRef,
ctype: PyObjectRef,
ctype: &PyObject,
vm: &VirtualMachine,
) -> PyResult {
// 1. cast_check_pointertype
if !cast_check_pointertype(&ctype, vm) {
if !cast_check_pointertype(ctype, vm) {
return Err(vm.new_type_error(format!(
"cast() argument 2 must be a pointer type, not {}",
ctype.class().name()
@@ -820,8 +820,8 @@ impl Constructor for PyCFuncPtr {
// Create the thunk (C-callable wrapper for the Python function)
let thunk = PyCThunk::new(
first_arg.clone(),
class_argtypes.clone(),
class_restype.clone(),
class_argtypes.as_deref(),
class_restype.as_deref(),
class_flags,
vm,
)?;
@@ -865,7 +865,7 @@ impl Constructor for PyCFuncPtr {
fn handle_internal_func(addr: usize, args: &FuncArgs, vm: &VirtualMachine) -> Option<PyResult> {
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 {
@@ -1940,18 +1940,18 @@ impl Debug for PyCThunk {
impl PyCThunk {
pub fn new(
callable: PyObjectRef,
arg_types: Option<PyObjectRef>,
res_type: Option<PyObjectRef>,
arg_types: Option<&PyObject>,
res_type: Option<&PyObject>,
flags: u32,
vm: &VirtualMachine,
) -> PyResult<Self> {
let arg_type_vec: Vec<PyTypeRef> = match arg_types {
Some(args) if !vm.is_none(&args) => extract_arg_types(&args, vm)?,
Some(args) if !vm.is_none(args) => extract_arg_types(args, vm)?,
_ => Vec::new(),
};
let res_type_ref: Option<PyTypeRef> = match res_type {
Some(ref rt) if !vm.is_none(rt) => Some(
Some(rt) if !vm.is_none(rt) => Some(
rt.to_owned()
.downcast::<PyType>()
.map_err(|_| vm.new_type_error("restype must be a ctypes type"))?,
+6 -6
View File
@@ -4,7 +4,7 @@ use crate::atomic_func;
use crate::protocol::{BufferDescriptor, PyBuffer, PyMappingMethods, PyNumberMethods};
use crate::types::{AsBuffer, AsMapping, AsNumber, Constructor, Initializer};
use crate::{
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine,
builtins::{PyBytes, PyInt, PyList, PySlice, PyStr, PyType, PyTypeRef},
class::StaticType,
function::{FuncArgs, OptionalArg},
@@ -24,9 +24,9 @@ pub(super) struct PyCPointerType(PyType);
impl Initializer for PyCPointerType {
type Args = FuncArgs;
fn init(zelf: crate::PyRef<Self>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &crate::Py<Self>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// Get the type as PyTypeRef
let obj: PyObjectRef = zelf.clone().into();
let obj: PyObjectRef = zelf.to_owned().into();
let new_type: PyTypeRef = obj
.downcast()
.map_err(|_| vm.new_type_error("expected type"))?;
@@ -79,7 +79,7 @@ impl Initializer for PyCPointerType {
&& let Ok(target_type) = type_attr.downcast::<PyType>()
&& let Some(mut target_info) = target_type.get_type_data_mut::<StgInfo>()
{
let zelf_obj: PyObjectRef = zelf.into();
let zelf_obj: PyObjectRef = zelf.to_owned().into();
target_info.pointer_type = Some(zelf_obj);
}
@@ -281,12 +281,12 @@ impl Constructor for PyCPointer {
impl Initializer for PyCPointer {
type Args = (OptionalArg<PyObjectRef>,);
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let (value,) = args;
if let OptionalArg::Present(val) = value
&& !vm.is_none(&val)
{
Self::set_contents(&zelf, val, vm)?;
Self::set_contents(zelf, val, vm)?;
}
Ok(())
}
+3 -3
View File
@@ -525,7 +525,7 @@ impl AsNumber for PyCSimpleType {
impl Initializer for PyCSimpleType {
type Args = FuncArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// type_init requires exactly 3 positional arguments: name, bases, dict
if args.args.len() != 3 {
return Err(vm.new_type_error(format!(
@@ -1052,10 +1052,10 @@ impl Constructor for PyCSimple {
impl Initializer for PyCSimple {
type Args = (OptionalArg,);
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// If an argument is provided, update the value
if let Some(value) = args.0.into_option() {
Self::set_value(zelf.into(), value, vm)?;
Self::set_value(zelf.to_owned().into(), value, vm)?;
}
Ok(())
}
+4 -4
View File
@@ -66,9 +66,9 @@ impl Constructor for PyCStructType {
impl Initializer for PyCStructType {
type Args = FuncArgs;
fn init(zelf: crate::PyRef<Self>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &crate::Py<Self>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// Get the type as PyTypeRef by converting PyRef<Self> -> PyObjectRef -> PyRef<PyType>
let obj: PyObjectRef = zelf.into();
let obj: PyObjectRef = zelf.to_owned().into();
let new_type: PyTypeRef = obj
.downcast()
.map_err(|_| vm.new_type_error("expected type"))?;
@@ -768,13 +768,13 @@ impl PyCStructure {
impl Initializer for PyCStructure {
type Args = FuncArgs;
fn init(zelf: crate::PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &crate::Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// Struct_init: handle positional and keyword arguments
let cls = zelf.class().to_owned();
// 1. Process positional arguments recursively through inheritance chain
if !args.args.is_empty() {
let consumed = Self::init_pos_args(&zelf, &cls, &args.args, &args.kwargs, 0, vm)?;
let consumed = Self::init_pos_args(zelf, &cls, &args.args, &args.kwargs, 0, vm)?;
if consumed < args.args.len() {
return Err(vm.new_type_error("too many initializers"));
+4 -4
View File
@@ -67,9 +67,9 @@ impl Constructor for PyCUnionType {
impl Initializer for PyCUnionType {
type Args = FuncArgs;
fn init(zelf: crate::PyRef<Self>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &crate::Py<Self>, _args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// Get the type as PyTypeRef by converting PyRef<Self> -> PyObjectRef -> PyRef<PyType>
let obj: PyObjectRef = zelf.into();
let obj: PyObjectRef = zelf.to_owned().into();
let new_type: PyTypeRef = obj
.downcast()
.map_err(|_| vm.new_type_error("expected type"))?;
@@ -637,13 +637,13 @@ impl PyCUnion {
impl Initializer for PyCUnion {
type Args = FuncArgs;
fn init(zelf: crate::PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &crate::Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// Struct_init: handle positional and keyword arguments
let cls = zelf.class().to_owned();
// 1. Process positional arguments recursively through inheritance chain
if !args.args.is_empty() {
let consumed = Self::init_pos_args(&zelf, &cls, &args.args, &args.kwargs, 0, vm)?;
let consumed = Self::init_pos_args(zelf, &cls, &args.args, &args.kwargs, 0, vm)?;
if consumed < args.args.len() {
return Err(vm.new_type_error("too many initializers"));
+16 -12
View File
@@ -550,16 +550,18 @@ mod _functools {
impl GetDescriptor for PyPartial {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
_cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
_cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
let obj = match obj {
Some(obj) if !vm.is_none(&obj) => obj,
_ => return Ok(zelf),
Some(obj) if !vm.is_none(obj) => obj,
_ => return Ok(zelf.to_owned()),
};
Ok(PyBoundMethod::new(obj, zelf).into_ref(&vm.ctx).into())
Ok(PyBoundMethod::new(obj.to_owned(), zelf.to_owned())
.into_ref(&vm.ctx)
.into())
}
}
@@ -895,16 +897,18 @@ mod _functools {
impl GetDescriptor for PyLruCacheWrapper {
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
_cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
_cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
let obj = match obj {
Some(obj) if !vm.is_none(&obj) => obj,
_ => return Ok(zelf),
Some(obj) if !vm.is_none(obj) => obj,
_ => return Ok(zelf.to_owned()),
};
Ok(PyBoundMethod::new(obj, zelf).into_ref(&vm.ctx).into())
Ok(PyBoundMethod::new(obj.to_owned(), zelf.to_owned())
.into_ref(&vm.ctx)
.into())
}
}
}
+28 -33
View File
@@ -36,7 +36,7 @@ const DEFAULT_BUFFER_SIZE: usize = 128 * 1024;
fn iobase_finalize(zelf: &PyObject, vm: &VirtualMachine) {
// If `closed` doesn't exist or can't be evaluated as bool, then the
// object is probably in an unusable state, so ignore.
let closed = match vm.get_attribute_opt(zelf.to_owned(), "closed") {
let closed = match vm.get_attribute_opt(zelf, "closed") {
Ok(Some(val)) => match val.try_to_bool(vm) {
Ok(b) => b,
Err(_) => return,
@@ -71,7 +71,7 @@ impl TryFromObject for Fildes {
let int = match obj.downcast::<int::PyInt>() {
Ok(i) => i,
Err(obj) => {
let fileno_meth = vm.get_attribute_opt(obj, "fileno")?.ok_or_else(|| {
let fileno_meth = vm.get_attribute_opt(&obj, "fileno")?.ok_or_else(|| {
vm.new_type_error("argument must be an int, or have a fileno() method.")
})?;
fileno_meth
@@ -1627,8 +1627,8 @@ mod _io {
}
#[pyslot]
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let zelf: PyRef<Self> = zelf.try_into_value(vm)?;
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let zelf: &Py<Self> = zelf.try_to_ref(vm)?;
let (raw, BufferSize { buffer_size }): (PyObjectRef, _) =
args.bind(vm).map_err(|e| {
let str_repr = e.__str__(vm).as_wtf8().to_owned();
@@ -2252,7 +2252,7 @@ mod _io {
type Args = (PyObjectRef, PyObjectRef, BufferSize);
fn init(
zelf: PyRef<Self>,
zelf: &Py<Self>,
(reader, writer, buffer_size): Self::Args,
vm: &VirtualMachine,
) -> PyResult<()> {
@@ -2427,10 +2427,10 @@ mod _io {
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__")?
.get_attribute_opt(cls.as_object(), "__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.to_owned(), "__getstate__")? {
let state = if let Some(getstate) = vm.get_attribute_opt(zelf, "__getstate__")? {
getstate.call((), vm)?
} else if let Ok(dict) = zelf.get_attr("__dict__", vm) {
dict
@@ -2771,11 +2771,7 @@ mod _io {
impl Initializer for TextIOWrapper {
type Args = (PyObjectRef, TextIOWrapperArgs);
fn init(
zelf: PyRef<Self>,
(buffer, args): Self::Args,
vm: &VirtualMachine,
) -> PyResult<()> {
fn init(zelf: &Py<Self>, (buffer, args): Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let mut data = zelf.lock_opt(vm)?;
*data = None;
@@ -2784,7 +2780,7 @@ mod _io {
let errors = args.errors.unwrap_or_else(|| vm.ctx.new_utf8_str("strict"));
Self::validate_errors(&errors, vm)?;
let has_read1 = vm.get_attribute_opt(buffer.clone(), "read1")?.is_some();
let has_read1 = vm.get_attribute_opt(&buffer, "read1")?.is_some();
let seekable = vm.call_method(&buffer, "seekable", ())?.try_to_bool(vm)?;
let newline = match args.newline {
@@ -2832,8 +2828,8 @@ mod _io {
Ok(())
}
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let zelf_ref: PyRef<Self> = zelf.try_into_value(vm)?;
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let zelf_ref: &Py<Self> = zelf.try_to_ref(vm)?;
{
let mut data = zelf_ref.lock_opt(vm)?;
*data = None;
@@ -2978,7 +2974,7 @@ mod _io {
|| err.fast_isinstance(vm.ctx.exceptions.attribute_error) =>
{
let name = vm
.get_attribute_opt(codec.as_tuple().to_owned().into(), "name")?
.get_attribute_opt(codec.as_tuple().as_object(), "name")?
.and_then(|obj| obj.downcast::<PyStr>().ok());
StatelessIncrementalEncoder {
encode: codec.get_encode_func().to_owned(),
@@ -2990,7 +2986,7 @@ mod _io {
}
Err(err) => return Err(err),
};
let encoding_name = vm.get_attribute_opt(incremental_encoder.clone(), "name")?;
let encoding_name = vm.get_attribute_opt(&incremental_encoder, "name")?;
let encode_func = encoding_name.and_then(|name| {
let name = name.downcast_ref::<PyStr>()?;
match name.to_str()? {
@@ -3202,7 +3198,7 @@ mod _io {
let Some(decoder) = &data.decoder else {
return Ok(None);
};
vm.get_attribute_opt(decoder.clone(), "newlines")
vm.get_attribute_opt(decoder, "newlines")
}
#[pygetset(name = "_CHUNK_SIZE")]
@@ -4091,16 +4087,16 @@ mod _io {
let mut result = Wtf8Buf::from(format!("<{type_name}"));
// Add name if present
if let Ok(Some(name)) = vm.get_attribute_opt(data.buffer.clone(), "name") {
if let Ok(Some(name)) = vm.get_attribute_opt(&data.buffer, "name") {
let name_repr = name.repr(vm)?;
result.push_wtf8(" name=".as_ref());
result.push_wtf8(name_repr.as_wtf8());
}
// Add mode if present (prefer the wrapper's attribute)
let mode_obj = match vm.get_attribute_opt(zelf.as_object().to_owned(), "mode") {
let mode_obj = match vm.get_attribute_opt(zelf.as_object(), "mode") {
Ok(Some(mode)) => Some(mode),
Ok(None) | Err(_) => match vm.get_attribute_opt(data.buffer.clone(), "mode") {
Ok(None) | Err(_) => match vm.get_attribute_opt(&data.buffer, "mode") {
Ok(Some(mode)) => Some(mode),
_ => None,
},
@@ -4234,7 +4230,7 @@ mod _io {
impl Initializer for IncrementalNewlineDecoder {
type Args = IncrementalNewlineDecoderArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let _ = args.errors;
let mut data = zelf.lock_opt(vm)?;
*data = Some(IncrementalNewlineDecoderData {
@@ -4432,7 +4428,7 @@ mod _io {
type Args = StringIONewArgs;
fn init(
zelf: PyRef<Self>,
zelf: &Py<Self>,
Self::Args { object, newline }: Self::Args,
_vm: &VirtualMachine,
) -> PyResult<()> {
@@ -4769,7 +4765,7 @@ mod _io {
impl Initializer for BytesIO {
type Args = BytesIOArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
if zelf.exports.load() > 0 {
return Err(
vm.new_buffer_error("Existing exports of data: object cannot be re-sized")
@@ -5558,8 +5554,7 @@ mod fileio {
use super::{_io::*, Offset, iobase_finalize};
use crate::host_env::crt_fd;
use crate::{
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject,
VirtualMachine,
AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine,
builtins::{PyBaseExceptionRef, PyUtf8Str, PyUtf8StrRef},
common::wtf8::Wtf8Buf,
convert::{IntoPyException, ToPyException},
@@ -5616,7 +5611,7 @@ mod fileio {
impl Initializer for FileIO {
type Args = FileIOArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
// TODO: let atomic_flag_works
let name = args.name;
// Check if bool is used as file descriptor
@@ -6095,7 +6090,7 @@ mod fileio {
mod winconsoleio {
use super::{_io::*, iobase_finalize};
use crate::{
AsObject, Py, PyObject, PyObjectRef, PyRef, PyResult, TryFromObject, VirtualMachine,
AsObject, Py, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine,
builtins::{PyBaseExceptionRef, PyUtf8StrRef},
common::{lock::PyMutex, wtf8::Wtf8Buf},
convert::{IntoPyException, ToPyException},
@@ -6185,12 +6180,12 @@ mod winconsoleio {
impl Initializer for WindowsConsoleIO {
type Args = WindowsConsoleIOArgs;
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> {
let nameobj = args.name;
if zelf.fd.load() >= 0 {
if zelf.closefd.load() {
internal_close(&zelf);
internal_close(zelf);
} else {
zelf.fd.store(-1);
}
@@ -6295,16 +6290,16 @@ mod winconsoleio {
if console_type == '\0' {
// Not a console at all
internal_close(&zelf);
internal_close(zelf);
return Err(vm.new_value_error("Cannot open non-console file"));
}
if writable && console_type != 'w' {
internal_close(&zelf);
internal_close(zelf);
return Err(vm.new_value_error("Cannot open console input buffer for writing"));
}
if readable && console_type != 'r' {
internal_close(&zelf);
internal_close(zelf);
return Err(vm.new_value_error("Cannot open console output buffer for reading"));
}
+2 -2
View File
@@ -1628,14 +1628,14 @@ fn run_string_in_new_subinterp(
match target.run_code_obj(code, scope) {
Ok(_) => Ok(0),
Err(exc) => {
target.print_exception(exc);
target.print_exception(&exc);
Ok(-1)
}
}
}
Err(err) => {
let exc = err.into_pyexception(target, Some(source));
target.print_exception(exc);
target.print_exception(&exc);
Ok(-1)
}
}
+1 -1
View File
@@ -1181,7 +1181,7 @@ pub(crate) mod _thread {
return Ok(dict);
};
let init_args = zelf.inner.state.lock().init_args.clone();
if let Err(err) = init(zelf.as_object().to_owned(), init_args, vm) {
if let Err(err) = init(zelf.as_object(), init_args, vm) {
zelf.remove_current_dict();
return Err(err);
}
+1 -1
View File
@@ -149,7 +149,7 @@ mod _warnings {
category,
level,
args.source.into_option(),
skip_prefixes,
skip_prefixes.as_deref(),
vm,
)
}
+11 -6
View File
@@ -697,7 +697,7 @@ mod builtins {
})?;
if let OptionalArg::Present(default) = default {
Ok(vm.get_attribute_opt(obj, attr)?.unwrap_or(default))
Ok(vm.get_attribute_opt(&obj, attr)?.unwrap_or(default))
} else {
obj.get_attr(attr, vm)
}
@@ -716,7 +716,7 @@ mod builtins {
name.class().name()
))
})?;
Ok(vm.get_attribute_opt(obj, attr)?.is_some())
Ok(vm.get_attribute_opt(&obj, attr)?.is_some())
}
#[pyfunction]
@@ -1254,7 +1254,13 @@ mod builtins {
.name
.downcast_ref::<PyStr>()
.ok_or_else(|| vm.new_type_error("module name must be a string"))?;
crate::import::import_module_level(name, args.globals, args.fromlist, args.level, vm)
crate::import::import_module_level(
name,
args.globals.as_deref(),
args.fromlist,
args.level,
vm,
)
}
#[pyfunction]
@@ -1287,8 +1293,7 @@ mod builtins {
}
continue;
}
let mro_entries =
vm.get_attribute_opt(base.clone(), identifier!(vm, __mro_entries__))?;
let mro_entries = vm.get_attribute_opt(base, identifier!(vm, __mro_entries__))?;
let entries = match mro_entries {
Some(meth) => meth.call((bases.clone(),), vm)?,
None => {
@@ -1357,7 +1362,7 @@ mod builtins {
// Prepare uses full __getattribute__ resolution chain.
let namespace = vm
.get_attribute_opt(metaclass.clone(), identifier!(vm, __prepare__))?
.get_attribute_opt(&metaclass, identifier!(vm, __prepare__))?
.map_or(Ok(vm.ctx.new_dict().into()), |prepare| {
let args = FuncArgs::new(vec![name_obj.clone(), bases.clone()], kwargs.clone());
prepare.call(args, vm)
+1 -1
View File
@@ -913,7 +913,7 @@ pub mod sys {
}
};
match vm.get_attribute_opt(module, &vm.ctx.new_str(attr_name)) {
match vm.get_attribute_opt(&module, &vm.ctx.new_str(attr_name)) {
Ok(Some(hook)) => hook.as_ref().call(args, vm),
_ => print_unimportable_module_warn(),
}
+29 -25
View File
@@ -327,12 +327,12 @@ pub(crate) type RichCompareFunc = fn(
pub(crate) type IterFunc = fn(PyObjectRef, &VirtualMachine) -> PyResult;
pub(crate) type IterNextFunc = fn(&PyObject, &VirtualMachine) -> PyResult<PyIterReturn>;
pub(crate) type DescrGetFunc =
fn(PyObjectRef, Option<PyObjectRef>, Option<PyObjectRef>, &VirtualMachine) -> PyResult;
fn(&PyObject, Option<&PyObject>, Option<&PyObject>, &VirtualMachine) -> PyResult;
pub(crate) type DescrSetFunc =
fn(&PyObject, PyObjectRef, PySetterValue, &VirtualMachine) -> PyResult<()>;
pub(crate) type AllocFunc = fn(PyTypeRef, usize, &VirtualMachine) -> PyResult;
pub(crate) type NewFunc = fn(PyTypeRef, FuncArgs, &VirtualMachine) -> PyResult;
pub(crate) type InitFunc = fn(PyObjectRef, FuncArgs, &VirtualMachine) -> PyResult<()>;
pub(crate) type InitFunc = fn(&PyObject, FuncArgs, &VirtualMachine) -> PyResult<()>;
pub(crate) type DelFunc = fn(&PyObject, &VirtualMachine) -> PyResult<()>;
// Sequence sub-slot function types
@@ -691,15 +691,19 @@ fn iternext_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<PyIterRetu
}
fn descr_get_wrapper(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult {
// A descriptor whose `__get__` is the descriptor itself resolves it by
// fetching `__get__` again, and none of that pushes a Python frame.
vm.with_recursion("while calling a Python object", || {
vm.call_special_method(&zelf, identifier!(vm, __get__), (obj, cls))
vm.call_special_method(
zelf,
identifier!(vm, __get__),
(obj.map(PyObject::to_owned), cls.map(PyObject::to_owned)),
)
})
}
@@ -718,8 +722,8 @@ fn descr_set_wrapper(
.map(drop)
}
fn init_wrapper(obj: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let res = vm.call_special_method(&obj, identifier!(vm, __init__), args)?;
fn init_wrapper(obj: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
let res = vm.call_special_method(obj, identifier!(vm, __init__), args)?;
if !vm.is_none(&res) {
return Err(vm.new_type_error(format!(
"__init__() should return None, not '{:.200}'",
@@ -1857,7 +1861,7 @@ pub trait DefaultConstructor: PyPayload + Default + core::fmt::Debug {
Self: Initializer,
{
let this = Self::default().into_ref(&vm.ctx);
Self::init(this.clone(), args, vm)?;
Self::init(&this, args, vm)?;
Ok(this)
}
}
@@ -1883,11 +1887,11 @@ pub trait Initializer: PyPayload {
#[inline]
#[pyslot]
fn slot_init(zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> {
#[cfg(debug_assertions)]
let class_name_for_debug = zelf.class().name().to_string();
let zelf = match zelf.try_into_value(vm) {
let zelf = match zelf.try_to_ref::<Self>(vm) {
Ok(zelf) => zelf,
Err(err) => {
#[cfg(debug_assertions)]
@@ -1911,7 +1915,7 @@ pub trait Initializer: PyPayload {
Self::init(zelf, args, vm)
}
fn init(zelf: PyRef<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()>;
fn init(zelf: &Py<Self>, args: Self::Args, vm: &VirtualMachine) -> PyResult<()>;
}
#[pyclass]
@@ -1957,9 +1961,9 @@ pub trait Callable: PyPayload {
pub trait GetDescriptor: PyPayload {
#[pyslot]
fn descr_get(
zelf: PyObjectRef,
obj: Option<PyObjectRef>,
cls: Option<PyObjectRef>,
zelf: &PyObject,
obj: Option<&PyObject>,
cls: Option<&PyObject>,
vm: &VirtualMachine,
) -> PyResult;
@@ -1969,22 +1973,22 @@ pub trait GetDescriptor: PyPayload {
}
#[inline]
fn _unwrap<'a>(
fn _unwrap<'a, 'b>(
zelf: &'a PyObject,
obj: Option<PyObjectRef>,
vm: &VirtualMachine,
) -> PyResult<(&'a Py<Self>, PyObjectRef)> {
obj: Option<&'b PyObject>,
vm: &'b VirtualMachine,
) -> PyResult<(&'a Py<Self>, &'b PyObject)> {
let zelf = Self::_as_pyref(zelf, vm)?;
let obj = vm.unwrap_or_none(obj);
let obj = obj.unwrap_or_else(|| vm.ctx.none.as_object());
Ok((zelf, obj))
}
#[inline]
fn _check<'a>(
fn _check<'a, 'b>(
zelf: &'a PyObject,
obj: Option<PyObjectRef>,
obj: Option<&'b PyObject>,
vm: &VirtualMachine,
) -> Option<(&'a Py<Self>, PyObjectRef)> {
) -> Option<(&'a Py<Self>, &'b PyObject)> {
// CPython descr_check
let obj = obj?;
// if (!PyObject_TypeCheck(obj, descr->d_type)) {
@@ -2001,8 +2005,8 @@ pub trait GetDescriptor: PyPayload {
}
#[inline]
fn _cls_is(cls: &Option<PyObjectRef>, other: &impl Borrow<PyObject>) -> bool {
cls.as_ref().is_some_and(|cls| other.borrow().is(cls))
fn _cls_is(cls: &Option<&PyObject>, other: &impl Borrow<PyObject>) -> bool {
cls.is_some_and(|cls| other.borrow().is(cls))
}
}
+19 -17
View File
@@ -52,8 +52,8 @@ impl PyMethod {
if let Some(descr_get) = descr_get
&& descr_cls.slots.descr_set.load().is_some()
{
let cls = cls.to_owned().into();
return descr_get(descr, Some(obj), Some(cls), vm).map(Self::Attribute);
return descr_get(descr.as_object(), Some(&obj), Some(cls.as_object()), vm)
.map(Self::Attribute);
}
descr_get
};
@@ -75,8 +75,8 @@ impl PyMethod {
func: attr,
}),
Some(descr_get) => {
let cls = cls.to_owned().into();
descr_get(attr, Some(obj), Some(cls), vm).map(Self::Attribute)
descr_get(attr.as_object(), Some(&obj), Some(cls.as_object()), vm)
.map(Self::Attribute)
}
None => Ok(Self::Attribute(attr)),
}
@@ -130,19 +130,21 @@ impl PyMethod {
func,
}
} else {
let obj_cls = obj_cls.to_owned().into();
let attr =
match vm.call_get_descriptor_specific(&func, Some(obj.to_owned()), Some(obj_cls)) {
Some(Ok(attr)) => attr,
Some(Err(e))
if !raise_attribute_error
&& e.fast_isinstance(vm.ctx.exceptions.attribute_error) =>
{
return Ok(None);
}
Some(Err(e)) => return Err(e),
None => func,
};
let attr = match vm.call_get_descriptor_specific(
&func,
Some(obj),
Some(obj_cls.as_object()),
) {
Some(Ok(attr)) => attr,
Some(Err(e))
if !raise_attribute_error
&& e.fast_isinstance(vm.ctx.exceptions.attribute_error) =>
{
return Ok(None);
}
Some(Err(e)) => return Err(e),
None => func,
};
Self::Attribute(attr)
};
Ok(Some(meth))
+6 -6
View File
@@ -1533,7 +1533,7 @@ impl VirtualMachine {
eprintln!(
"importlib initialization failed. This is critical for many complicated packages."
);
self.print_exception(e);
self.print_exception(&e);
}
#[cfg(not(feature = "host_env"))]
@@ -1548,7 +1548,7 @@ impl VirtualMachine {
eprintln!(
"encodings initialization failed. Only utf-8 encoding will be supported."
);
self.print_exception(e);
self.print_exception(&e);
}
} else {
// Here may not be the best place to give general `path_list` advice,
@@ -3435,7 +3435,7 @@ impl VirtualMachine {
pub fn get_attribute_opt<'a>(
&self,
obj: PyObjectRef,
obj: &PyObject,
attr_name: impl AsPyStr<'a>,
) -> PyResult<Option<PyObjectRef>> {
let attr_name = attr_name.as_pystr(&self.ctx);
@@ -3736,7 +3736,7 @@ impl VirtualMachine {
}
1
} else if exc.fast_isinstance(self.ctx.exceptions.keyboard_interrupt) {
self.print_exception(exc);
self.print_exception(&exc);
cfg_select! {
unix => {
if crate::host_env::signal::set_sigint_default_onstack().is_ok() {
@@ -3752,7 +3752,7 @@ impl VirtualMachine {
_ => 1,
}
} else {
self.print_exception(exc);
self.print_exception(&exc);
1
}
}
@@ -3879,7 +3879,7 @@ mod tests {
.unwrap();
if let Err(e) = vm.run_code_obj(code_obj, scope) {
vm.print_exception(e);
vm.print_exception(&e);
panic!();
}
})
+1 -1
View File
@@ -467,7 +467,7 @@ impl VirtualMachine {
cls.name()
);
let obj = T::slot_new(cls, args.clone(), self)?;
T::slot_init(obj.clone(), args, self)?;
T::slot_init(&obj, args, self)?;
obj.downcast().map_err(|obj| {
self.new_type_error(format!(
"payload constructor returned '{}'",
+7 -8
View File
@@ -37,7 +37,7 @@ impl VirtualMachine {
}
},
_ => {
self.print_exception(exc);
self.print_exception(&exc);
self.flush_std();
panic!("{msg}")
}
@@ -106,20 +106,19 @@ impl VirtualMachine {
pub fn call_get_descriptor_specific(
&self,
descr: &PyObject,
obj: Option<PyObjectRef>,
cls: Option<PyObjectRef>,
obj: Option<&PyObject>,
cls: Option<&PyObject>,
) -> Option<PyResult> {
let descr_get = descr.class().slots.descr_get.load()?;
Some(descr_get(descr.to_owned(), obj, cls, self))
Some(descr_get(descr, obj, cls, self))
}
pub fn call_get_descriptor(&self, descr: &PyObject, obj: PyObjectRef) -> Option<PyResult> {
let cls = obj.class().to_owned().into();
self.call_get_descriptor_specific(descr, Some(obj), Some(cls))
pub fn call_get_descriptor(&self, descr: &PyObject, obj: &PyObject) -> Option<PyResult> {
self.call_get_descriptor_specific(descr, Some(obj), Some(obj.class().as_object()))
}
pub fn call_if_get_descriptor(&self, attr: &PyObject, obj: PyObjectRef) -> PyResult {
self.call_get_descriptor(attr, obj)
self.call_get_descriptor(attr, &obj)
.unwrap_or_else(|| Ok(attr.to_owned()))
}
+8 -9
View File
@@ -137,7 +137,7 @@ fn get_warnings_attr(
}
};
vm.get_attribute_opt(module, attr_name)
vm.get_attribute_opt(&module, attr_name)
}
/// Get the warnings filters list from `sys.modules['warnings'].filters`,
@@ -212,7 +212,7 @@ pub(crate) fn get_source_line(
}
};
let Some(get_source) = vm.get_attribute_opt(loader, vm.ctx.intern_str("get_source"))? else {
let Some(get_source) = vm.get_attribute_opt(&loader, vm.ctx.intern_str("get_source"))? else {
return Ok(None);
};
let source = get_source.call((module_name,), vm)?;
@@ -474,17 +474,16 @@ pub fn warn_with_skip(
category: Option<PyTypeRef>,
mut stack_level: isize,
source: Option<PyObjectRef>,
skip_file_prefixes: Option<PyTupleRef>,
skip_file_prefixes: Option<&Py<PyTuple>>,
vm: &VirtualMachine,
) -> PyResult<()> {
if let Some(ref prefixes) = skip_file_prefixes
if let Some(prefixes) = skip_file_prefixes
&& !prefixes.is_empty()
&& stack_level < 2
{
stack_level = 2;
}
let (filename, lineno, module, registry) =
setup_context(stack_level, skip_file_prefixes.as_deref(), vm)?;
let (filename, lineno, module, registry) = setup_context(stack_level, skip_file_prefixes, vm)?;
warn_explicit(
category, message, filename, lineno, module, registry, None, source, vm,
)
@@ -595,7 +594,7 @@ pub fn warn_explicit(
call_show_warning(
category,
text,
&text,
message,
filename,
lineno,
@@ -609,7 +608,7 @@ pub fn warn_explicit(
#[allow(clippy::too_many_arguments)]
fn call_show_warning(
category: PyTypeRef,
text: PyStrRef,
text: &Py<PyStr>,
message: PyObjectRef,
filename: PyStrRef,
lineno: usize,
@@ -620,7 +619,7 @@ fn call_show_warning(
) -> PyResult<()> {
let Some(show_fn) = get_warnings_attr(vm, identifier!(vm, _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(());
};
+1 -1
View File
@@ -446,7 +446,7 @@ mod _js {
}
fn cast(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult<Self> {
let then = vm.get_attribute_opt(obj.clone(), "then")?;
let then = vm.get_attribute_opt(&obj, "then")?;
let value = if let Some(then) = then.filter(|obj| obj.is_callable()) {
PromiseKind::PyProm { then }
} else {
+1 -1
View File
@@ -14,7 +14,7 @@ fn run(vm: &vm::VirtualMachine) -> vm::PyResult<()> {
let res = vm.run_code_obj(vm.ctx.new_code(module), scope);
if let Err(exc) = res {
vm.print_exception(exc);
vm.print_exception(&exc);
}
Ok(())
+1 -1
View File
@@ -76,7 +76,7 @@ def fib(n):
}
}
Err(exc) => {
vm.print_exception(exc);
vm.print_exception(&exc);
}
}
}
+2 -2
View File
@@ -213,7 +213,7 @@ pub fn run_shell(vm: &VirtualMachine, scope: Scope) -> PyResult<()> {
vm.ctx.exceptions.os_error.to_owned(),
format!("{num:?}").into(),
);
vm.print_exception(os_error);
vm.print_exception(&os_error);
break;
}
ReadlineResult::Other(err) => {
@@ -231,7 +231,7 @@ pub fn run_shell(vm: &VirtualMachine, scope: Scope) -> PyResult<()> {
repl.save_history(&repl_history_path).unwrap();
return Err(exc);
}
vm.print_exception(exc);
vm.print_exception(&exc);
}
flush_stdio(vm);
}
+2 -2
View File
@@ -40,7 +40,7 @@ fn pyperformance_benchmarks_run_in_rustpython() {
.unwrap_or_else(|err| panic!("failed to compile {}: {err}", path.display()));
let scope = vm.new_scope_with_builtins();
if let Err(err) = vm.run_code_obj(code, scope) {
vm.print_exception(err);
vm.print_exception(&err);
panic!("failed to execute {}", path.display());
}
});
@@ -78,7 +78,7 @@ assert decimal.getcontext().prec == decimal_precision
.interpreter()
.enter(|vm| {
if let Err(err) = vm.run_simple_string(source) {
vm.print_exception(err);
vm.print_exception(&err);
panic!("pyperformance benchmarks leaked interpreter state");
}
});