Skip to content
Merged
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
55 changes: 39 additions & 16 deletions src/core/IronPython/Runtime/Binding/PythonProtocol.Operations.cs
Original file line number Diff line number Diff line change
Expand Up @@ -689,12 +689,12 @@ private static NewExpression MakeEnumeratorResult(Expression tmp) {
SlotOrFunction rbinder;
PythonTypeSlot fSlot;
PythonTypeSlot rSlot;
GetOperatorMethods(types, operation, PythonContext.GetPythonContext(binder), out fbinder, out rbinder, out fSlot, out rSlot);
GetOperatorMethods(types, operation, PythonContext.GetPythonContext(binder), out fbinder, out rbinder, out fSlot, out rSlot, out bool reverseFirst);

return MakeBinaryOperatorResult(types, binder, operation, fbinder, rbinder, fSlot, rSlot, errorSuggestion);
return MakeBinaryOperatorResult(types, binder, operation, fbinder, rbinder, fSlot, rSlot, reverseFirst, errorSuggestion);
}

private static void GetOperatorMethods(DynamicMetaObject/*!*/[]/*!*/ types, PythonOperationKind oper, PythonContext state, out SlotOrFunction fbinder, out SlotOrFunction rbinder, out PythonTypeSlot fSlot, out PythonTypeSlot rSlot) {
private static void GetOperatorMethods(DynamicMetaObject/*!*/[]/*!*/ types, PythonOperationKind oper, PythonContext state, out SlotOrFunction fbinder, out SlotOrFunction rbinder, out PythonTypeSlot fSlot, out PythonTypeSlot rSlot, out bool reverseFirst) {
oper &= ~PythonOperationKind.InPlace;

string op, rop;
Expand Down Expand Up @@ -759,17 +759,29 @@ private static void GetOperatorMethods(DynamicMetaObject/*!*/[]/*!*/ types, Pyth
}
}

// TODO: this is incorrect - if the rslot returns NotImplemented then fslot is never called and a TypeError will be raised (https://github.com/IronLanguages/ironpython3/issues/1479)
if (fParent != null && (rbinder.Success || rSlot != null) && rParent != fParent && rParent.IsSubclassOf(fParent)) {
// Python says if x + subx and subx defines __r*__ we should call r*.
fbinder = SlotOrFunction.Empty;
fSlot = null;
}
// The reverse operator is tried before the forward one:
// - Python says if x + subx and subx defines __r*__ we should call r*.
// - if the left operand is a sequence and the right operand defines __radd__, we should call __radd__.
// The forward operator is still used if the reverse one returns NotImplemented.
reverseFirst = fParent != null && (rbinder.Success || rSlot != null) && rParent != fParent &&
(rParent.IsSubclassOf(fParent) || (oper == PythonOperationKind.Add && isSequence));

// TODO: this is incorrect - if the rslot returns NotImplemented then fslot is never called and a TypeError will be raised (https://github.com/IronLanguages/ironpython3/issues/560)
if (oper == PythonOperationKind.Add && fParent != null && (rbinder.Success || rSlot != null) && rParent != fParent && isSequence) {
// if the left operand is a sequence and the right operand defines __radd__, we should call __radd__.
fbinder = SlotOrFunction.Empty;
if (rSlot != null && types[0].GetLimitType() == typeof(int) && typeof(Extensible<BigInteger>).IsAssignableFrom(types[1].GetLimitType())) {
// The operators of Int32 do not accept subclasses of int, which are normally handled by the
// reverse operator that the subclass inherits. If the subclass overrides it, call the override
// first and fall back to the forward operator applied to both values as BigInteger.
reverseFirst = true;
DynamicMetaObject[] values = {
new DynamicMetaObject(
AstUtils.Convert(AstUtils.Convert(types[0].Expression, typeof(int)), typeof(BigInteger)),
BindingRestrictions.Empty
),
new DynamicMetaObject(
Ast.Property(AstUtils.Convert(types[1].Expression, typeof(Extensible<BigInteger>)), nameof(Extensible<BigInteger>.Value)),
BindingRestrictions.Empty
),
};
SlotOrFunction.TryGetBinder(state, values, op, null, out fbinder, out _);
fSlot = null;
}
}
Expand All @@ -790,7 +802,7 @@ private static bool IsSequence(DynamicMetaObject/*!*/ metaObject) {
return false;
}

private static DynamicMetaObject/*!*/ MakeBinaryOperatorResult(DynamicMetaObject/*!*/[]/*!*/ types, DynamicMetaObjectBinder/*!*/ operation, PythonOperationKind op, SlotOrFunction/*!*/ fCand, SlotOrFunction/*!*/ rCand, PythonTypeSlot fSlot, PythonTypeSlot rSlot, DynamicMetaObject errorSuggestion) {
private static DynamicMetaObject/*!*/ MakeBinaryOperatorResult(DynamicMetaObject/*!*/[]/*!*/ types, DynamicMetaObjectBinder/*!*/ operation, PythonOperationKind op, SlotOrFunction/*!*/ fCand, SlotOrFunction/*!*/ rCand, PythonTypeSlot fSlot, PythonTypeSlot rSlot, bool reverseFirst, DynamicMetaObject errorSuggestion) {
Assert.NotNull(operation, fCand, rCand);

SlotOrFunction fTarget, rTarget;
Expand All @@ -809,14 +821,25 @@ private static bool IsSequence(DynamicMetaObject/*!*/ metaObject) {
}
}

if (!SlotOrFunction.GetCombinedTargets(fCand, rCand, out fTarget, out rTarget) &&
bool hasTargets = SlotOrFunction.GetCombinedTargets(fCand, rCand, out fTarget, out rTarget);
if (reverseFirst && fCand.Success) {
// the forward operator is only a fallback, so keep it even if it requires more conversions
fTarget = fCand;
}

if (!hasTargets &&
fSlot == null &&
rSlot == null &&
bodyBuilder.NoConditions) {
return MakeRuleForNoMatch(operation, op, errorSuggestion, types);
}

if (MakeOneTarget(PythonContext.GetPythonContext(operation), fTarget, fSlot, bodyBuilder, false, types)) {
if (reverseFirst) {
if (MakeOneTarget(state, rTarget, rSlot, bodyBuilder, true, types) &&
MakeOneTarget(state, fTarget, fSlot, bodyBuilder, false, types)) {
bodyBuilder.FinishCondition(MakeBinaryThrow(operation, op, types).Expression, typeof(object));
}
} else if (MakeOneTarget(PythonContext.GetPythonContext(operation), fTarget, fSlot, bodyBuilder, false, types)) {
if (rSlot != null) {
MakeSlotCall(PythonContext.GetPythonContext(operation), types, bodyBuilder, rSlot, true);
bodyBuilder.FinishCondition(MakeBinaryThrow(operation, op, types).Expression, typeof(object));
Expand Down
35 changes: 35 additions & 0 deletions tests/suite/test_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -3268,6 +3268,41 @@ class C:
self.assertEqual(C.b, 10)
self.assertEqual(x, 10)

def test_reverse_operator_returning_not_implemented(self):
# https://github.com/IronLanguages/ironpython3/issues/1479
import operator
calls = []
def subclass(base, name):
def method(self, other):
calls.append(name)
return NotImplemented
return type('sub', (base,), {name: method})

operators = ('add', 'sub', 'mul', 'truediv', 'floordiv', 'mod', 'pow', 'and_', 'or_', 'xor', 'lshift', 'rshift')
for name in operators:
op = getattr(operator, name)
sub = subclass(int, '__r%s__' % name.rstrip('_'))
for left in (6, 2**70):
del calls[:]
self.assertEqual(op(left, sub(2)), op(left, 2))
self.assertEqual(len(calls), 1) # the reverse operator is tried first

for name in ('add', 'sub', 'mul', 'truediv'):
sub = subclass(float, '__r%s__' % name)
self.assertEqual(getattr(operator, name)(6.0, sub(2.0)), getattr(operator, name)(6.0, 2.0))

for left, right in (([1], [2]), ((1,), (2,)), (b'a', b'b')):
del calls[:]
self.assertEqual(left + subclass(type(right), '__radd__')(right), left + right)
self.assertEqual(calls, ['__radd__'])

# nothing to fall back to
class R:
def __radd__(self, other): return NotImplemented
for left in (1, 'a', [1], (), R()):
with self.assertRaises(TypeError):
left + R()

def test_private_names_in_fstrings(self):
# https://github.com/IronLanguages/ironpython3/issues/1421
class C:
Expand Down
Loading