HaxeFoundation / HaxeFoundation/haxe

Inline constructors, return new and unused variable elimination

Open
#5,472 8 comments 0 reactions 1 assignee Claimed by @Simn View on GitHub
bug feature-analyzer
Dominant language
Haxe
Stars
6.9k
Forks
715
Avg merge
2d 2h
Merged PRs (30d)
11

Description

I have a class that is purely inline and in another class I have properties of type of this class. And in setter I have to return result of assigment, but to keep class pure inline I have to return new instance with the same value. Pseudocode:

```
class Vector2 {
@:extern public inline function new(x, y)
}
class MyObject {
var x;
var y;
var position(get, set):Vector2;
function set_position(v:Vector2):Vector2 {
x = v.x;
y = v.y;
//return v; - this results in 'Extern constructor could not be inlined'
return new Vector2(x, y); // this works
}
}
```

But 'return new Vector2(x,y)' creates Vector2 object on heap in case the result of the assigment was not used. Here is my minimal example:

``` haxe
package;

class Foo {

var _v:String;

@:extern public inline function new(v:String) _v = v;

public inline function setFrom(another:Foo):Foo {
trace('old:$_v, new:${another._v}');
_v = another._v;
return new Foo(_v);
}

}

class Main {

static function main() {
test0("0_f", "0_f2");
test1("1_f", "1_f2");
test2("1_f", "1_f2");
}

/* Compiles to:
Main.test0 = function(v,v2) {
console.log("old:" + v2 + ", new:" + v);
new Foo(v); // this should be eliminated because resulting variable is not used
}
*/
static function test0(v:String, v2:String) {
var f = new Foo(v);
var f2 = new Foo(v2);
f2.setFrom(f);
}

/* Compiles to:
Main.test1 = function(v,v2) {
console.log("old:" + v2 + ", new:" + v);
// no 'new Foo'
}
*/
static function test1(v:String, v2:String) {
var f = new Foo(v);
var f2 = new Foo(v2);
var f3 = f2.setFrom(f);
}

/* Compiles to
Main.test2 = function(v,v2) {
console.log("old:" + v2 + ", new:" + v);
console.log("old:" + "f4" + ", new:" + v);
};
Inlining works great!
*/
static function test2(v:String, v2:String) {
var f = new Foo(v);
var f2 = new Foo(v2);
var f3 = f2.setFrom(f);

var f4 = new Foo('f4');
var t = f4.setFrom(f3);
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.