Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 32 additions & 35 deletions crates/vm/src/builtins/frame_locals_proxy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,12 @@ use crate::{
atomic_func,
class::{PyClassDef, PyClassImpl},
frame::FrameObjectRef,
function::{FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue},
function::{Either, FuncArgs, OptionalArg, PyComparisonValue},
object::{Traverse, TraverseFn},
protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods},
recursion::ReprGuard,
types::{
AsMapping, AsNumber, AsSequence, Comparable, Constructor, Iterable, PyComparisonOp,
Representable,
AsMapping, AsNumber, AsSequence, Constructor, Iterable, PyComparisonOp, Representable,
},
};
use rustpython_common::lock::LazyLock;
Expand Down Expand Up @@ -173,18 +172,39 @@ impl FrameLocalsProxy {
}

#[pyclass(
with(
Constructor,
AsMapping,
AsSequence,
AsNumber,
Iterable,
Comparable,
Representable
),
with(Constructor, AsMapping, AsSequence, AsNumber, Iterable, Representable),
flags(IMMUTABLETYPE)
)]
impl Py<FrameLocalsProxy> {
#[pyslot]
fn slot_richcompare(
zelf: &PyObject,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
) -> PyResult<Either<PyObjectRef, PyComparisonValue>> {
let zelf = zelf.downcast_ref::<FrameLocalsProxy>().ok_or_else(|| {
vm.new_type_error(format!(
"unexpected payload for {}",
op.method_name(&vm.ctx).as_str()
))
})?;
if let Some(other) = other.downcast_ref::<FrameLocalsProxy>() {
return op
.eq_only(|| Ok(PyComparisonValue::Implemented(zelf.frame.is(&other.frame))))
.map(Either::B);
}
if other.downcastable::<PyDict>() {
// CPython compares a fresh dict to the other operand using the
// original operation, preserving any reflected result as-is.
let snapshot: PyObjectRef = zelf.snapshot(vm)?.into();
return snapshot
.rich_compare(other.to_owned(), op, vm)
.map(Either::A);
}
Ok(Either::B(PyComparisonValue::NotImplemented))
}

#[pymethod]
fn keys(&self, vm: &VirtualMachine) -> PyResult<PyObjectRef> {
Ok(vm.ctx.new_list(self.keys_vec(vm)?).into())
Expand Down Expand Up @@ -335,29 +355,6 @@ impl Iterable for FrameLocalsProxy {
}
}

impl Comparable for FrameLocalsProxy {
fn cmp(
zelf: &Py<Self>,
other: &PyObject,
op: PyComparisonOp,
vm: &VirtualMachine,
) -> PyResult<PyComparisonValue> {
op.eq_only(|| {
if let Some(other) = other.downcast_ref::<Self>() {
return Ok(PyComparisonValue::Implemented(zelf.frame.is(&other.frame)));
}
if other.downcast_ref::<PyDict>().is_none() {
return Ok(PyComparisonValue::NotImplemented);
}
let self_dict: PyObjectRef = zelf.snapshot(vm)?.into();
let res = self_dict.rich_compare(other.to_owned(), PyComparisonOp::Eq, vm)?;
PyArithmeticValue::from_object(vm, res)
.map(|o| o.try_to_bool(vm))
.transpose()
})
}
}

impl Representable for FrameLocalsProxy {
fn repr_wtf8(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<Wtf8Buf> {
if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) {
Expand Down
27 changes: 27 additions & 0 deletions extra_tests/snippets/vm_frame_locals.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,33 @@ def exercise():

self.assertEqual(exercise(), (1, 2, 1))

def test_proxy_dict_subclass_preserves_comparison_result(self):
class ReflectedDict(dict):
def __eq__(self, other):
return ("eq", other)

def __ne__(self, other):
return ("ne", other)

def __gt__(self, other):
return ("gt", other)

def make_proxy():
x = 1
return sys._getframe().f_locals

proxy = make_proxy()
other = ReflectedDict()
self.assertEqual(proxy == other, ("eq", {"x": 1}))
self.assertEqual(proxy != other, ("ne", {"x": 1}))
self.assertEqual(proxy < other, ("gt", {"x": 1}))
self.assertEqual(proxy, {"x": 1})
self.assertNotEqual(proxy, make_proxy())
# The comparison method is free to mutate its snapshot, not the frame.
result = proxy == other
result[1]["x"] = 42
self.assertEqual(proxy["x"], 1)

def test_proxy_hash_comparison_and_union_dispatch(self):
class Reflected:
def __ror__(self, other):
Expand Down
Loading