alliedmodders / sourcepawn

A small, statically typed scripting language.
Other
369 stars 63 forks source link

Operator overloads don't work with enum structs #511

Open fakuivan opened 4 years ago

fakuivan commented 4 years ago

The following code does not compile on spcomp 1.11

enum struct Vector3 {
    float x;
    float y;
    float z;
    float volume() {
        return this.x*this.y*this.z;
    }
}

stock Vector3[] operator+(const Vector3 this_, const Vector3 other) {
    Vector3 result;
    result.x = this_.x + other.x;
    result.y = this_.y + other.y;
    result.z = this_.z + other.z;
    return result;
}

// returns a scalar, also doesn't work
stock float operator*(const Vector3 this_, const Vector3 other) {
    return this_.x * other.x + this_.y * other.y + this_.z * other.z;
}

Even though a more silly example is possible using methodmaps

methodmap Int {
    public Int(int value) {
        return view_as<Int>(value);
    }
    property int Value {
        public get() {
            return view_as<int>(this);
        }
    }
}

stock Int operator+(Int this_, Int other) {
    return Int(this_.Value - other.Value);
}

public void OnPluginStart()
{
    PrintToServer("Fake sum: %i", (Int(4) + Int(5)).Value);
}

Having overloads for enum structs would be nice for integral types that do not fit on a single cell, since it would allow us to transparently do things like pointer math or big timestamp deltas. For non scalar types like vectors, the * operator could be used to compute dot products or things like that.

dvander commented 4 years ago

This isn't on my short list of things to do, but it would be nice to have. The current compiler infrastructure makes it very difficult to implement so it's probably gated on the array rewrite + new parser being completed.