IronLanguages / main

Work for this repo has moved to https://github.com/IronLanguages/ironpython2
1.16k stars 347 forks source link

IronPython ignores overridden TryUnaryOperation of DynamicObject #1064

Open ironpythonbot opened 9 years ago

ironpythonbot commented 9 years ago

IronPython (2.7.3) seems to not check the TryUnaryOperation with ExpressionType.IsFalse and ExpressionType.IsTrue for performing short-circuit evaluation of the logical AND and OR operations.

Here's an example that uses a class that inherits from DynamicObject. In C#, it works perfectly, but produces a wrong result if used in an IronPython expression. Is that behavior expected or a bug? How can i get IronPython to behave the same way as C#?

* The class: *

public class Dyn : DynamicObject
{
    private readonly string text;

    public Dyn(string text)
    {
        this.text = text;
    }

    public override string ToString()
    {
        return this.text;
    }

    public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result)
    {
        result = new Dyn(this + " " + binder.Operation + " " + arg);
        return true;
    }

    public override bool TryUnaryOperation(UnaryOperationBinder binder, out object result)
    {
        switch (binder.Operation)
        {
            case ExpressionType.IsFalse:
            case ExpressionType.IsTrue:
                result = false;
                return true;
        }

        return base.TryUnaryOperation(binder, out result);
    }
}

* The usage: *

dynamic a = new Dyn("a");
dynamic b = new Dyn("b");
dynamic c = new Dyn("c");

var correct = a && b || c;

var engine = Python.CreateEngine();
var scope = engine.CreateScope();
scope.SetVariable("a", a);
scope.SetVariable("b", b);
scope.SetVariable("c", c);
var incorrect = engine.Execute("a and b or c", scope);

Console.WriteLine("Correct: " + correct);
Console.WriteLine("Incorrect: " + incorrect);

* Prints: *

Correct: a And b Or c
Incorrect: b

Work Item Details

Original CodePlex Issue: Issue 33978 Status: Proposed Reason Closed: Unassigned Assigned to: Unassigned Reported on: Apr 18, 2013 at 11:48 AM Reported by: Rauhotz Updated on: Jul 21, 2013 at 7:07 AM Updated by: jdhardy

hfoffani commented 8 years ago

I was able to reproduce it using IPY 2.7.6.3 version. I have attached a zip file with the code to build the code provided by the OP. test1064.zip

Reported by @hfoffani

hfoffani commented 8 years ago

As gist: https://gist.github.com/hfoffani/48227a39971e91e427e77caa1e322c3d