Skip to content

Custom binary operators not supported #21

@modernist

Description

@modernist

A ParserException occurs when attempting to evaluate an expression that uses custom binary operators on objects. Add the following code to OperatorsTest.cs to reproduce.

[TestMethod]
public void Can_use_overloaded_binary_operators()
{
    var target = new Interpreter();

    var x = new TypeWithOverloadedBinaryOperators(3);
    target.SetVariable("x", x);

    string y = "5";
    Assert.IsFalse(x == y);
    Assert.IsFalse(target.Eval<bool>("x == y", new Parameter("y", y)));

    y = "3";
    Assert.IsTrue(x == y);
    Assert.IsTrue(target.Eval<bool>("x == y", new Parameter("y", y)));

    Assert.IsFalse(target.Eval<bool>("x == \"4\""));
    Assert.IsTrue(target.Eval<bool>("x == \"3\""));
}

struct TypeWithOverloadedBinaryOperators
{
    private int _value;

    public TypeWithOverloadedBinaryOperators(int value)
    {
        _value = value;
    }

    public static bool operator ==(TypeWithOverloadedBinaryOperators instance, string value)
    {
        return instance._value.ToString().Equals(value);
    }

    public static bool operator !=(TypeWithOverloadedBinaryOperators instance, string value)
    {
        return !instance._value.ToString().Equals(value);
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;
        if (obj is TypeWithOverloadedBinaryOperators)
        {
            return this._value.Equals(((TypeWithOverloadedBinaryOperators)obj)._value);
        }
        return base.Equals(obj);
    }

    public override int GetHashCode()
    {
        return _value.GetHashCode();
    }
}

causes the following:

Operator '==' incompatible with operand types 'TypeWithOverloadedBinaryOperators' and 'String' (at index 2).
       at DynamicExpresso.ExpressionParser.CheckAndPromoteOperands(Type signatures, String opName, Expression& left, Expression& right, Int32 errorPos)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions