Search code examples
d

Passing values between in and out contracts in D


I'm new to D. I'm starting to utilize contracts and I think they are wonderful. However, I can't seem to find in the documentation where I can store local values available to the contracts like so...

struct Vector2(T) {
    T x = 0;
    T y = 0;

    Vector2!T opBinary(string op)(const ref Vector2!T rhs)
        if(op == "+" || op == "-" || op == "*" || op == "/")
    in {
        T prevx = this.x;
        T prevy = this.y;
    }
    out {
        static if(isFloatingPoint!T) {
            assert(mixin("approxEqual(this.x, prevx"~op~"rhs.x)"));
            assert(mixin("approxEqual(this.y, prevy"~op~"rhs.y)"));
        } else {
            assert(mixin("this.x == (prevx"~op~"rhs.x)"));
            assert(mixin("this.y == (prevy"~op~"rhs.y)"));
        }
    }
    body {
        Vector2!T ret;
        mixin("ret.x = this.x"~op~"rhs.x;");
        mixin("ret.y = this.y"~op~"rhs.y;");
        return ret;
    }
}

I need the value of x and y before the body is executed so that I may correctly verify the result in the out block. However, prevx and prevy obviously cannot travel between scopes. Is there some method of passing data between the in and out contracts?


Solution

  • Alas, there isn't. Best you can do is store it in some other variable on the outside and you can hit trouble there with recursion and such :(