Description
Feature suggestion
Hi,
I had this idea for C#-style structs that I believe could be implemented using a Transform.
I know structs have been brought up a couple of times, so there's clearly some demand.
Take this code :
@struct export class Vector2 {
x: f32 = 0;
y: f32 = 0;
constructor(x: f32, y: f32) {
x = x;
y = y;
}
}
export class Test {
position: Vector2 = new Vector2(0, 0);
}
That could be transformed into this :
@final @unmanaged export class Vector2 {
x: f32 = 0;
y: f32 = 0;
@inline constructor(x: f32, y: f32) {
let ret = changetype<Vector2>(memory.data(sizeof<Vector2>()));
ret.x = x;
ret.y = y;
return ret;
}
}
export class Test {
private _position_x: f32 = 0;
private _position_y: f32 = 0;
@inline get position(): Vector2 {
return new Vector2(this._position_x, this._position_y);
}
set position(value: Vector2) {
this._position_x = value.x;
this._position_y = value.y;
}
}
Which essentially makes the Vector2 class allocate on the stack when instantiated, while still being able to assign it to objects.
Obviously it gets more complex with nested structs and generics involved, and things like offsetof("position") would also need to be transformed, and respecting the original's constructor code would become tricky.
Also, I believe it would need to turn things like this :
let v1 = new Vector2(0, 0);
let v2 = v1;
Into something like this :
let v1 = new Vector2(0, 0);
let v2 = changetype<Vector2>(memory.data(sizeof<Vector2>()));
memory.copy(changetype<usize>(v1), changetype<usize>(v2), sizeof<Vector2>());
Not entirely sure how to deal with passing it around as a parameter or returning it, because my understanding of how memory works in AssemblyScript is a bit limited.
Would love to hear some thoughts on this idea.