HaxeFoundation / HaxeFoundation/haxe

[Suggestion] An option to "super-flatten" JS

Open
#6,602 2 comments 0 reactions 0 assignees View on GitHub
enhancement platform-javascript
Dominant language
Haxe
Stars
6.9k
Forks
715
Avg merge
2d 2h
Merged PRs (30d)
11

Description

I've originally brought this up [a long time ago](https://twitter.com/YellowAfterlife/status/679956868278665216), and maybe it's about time to file an issue about this.

Anyway, on flattening structures: optimizers like Google Closure _love_ flat structures. Say, you have
```haxe
class Test {
static function main() {
trace("hi");
}
}
```
which expectedly compiles to
```js
(function () { "use strict";
var Test = function() { };
Test.main = function() {
console.log("Test.hx:3:","hi");
};
Test.main();
})();
```
Passing this through Closure at Advanced level of optimizations yields a somewhat-predictable result - your class is still there:
```
(function() {
function a() {
}
a.a = function() {
console.log("Test.hx:3:", "hi");
};
a.a();
})();
```
If you flatten the class, however,
```js
(function () { "use strict";
function Test_main() {
console.log("Test.hx:3:","hi");
};
Test_main();
})();
```
things are different - Closure is now sure of the definition not being reassigned at runtime and inlines it completely:
```js
console.log("Test.hx:3:", "hi");
```
This also allows Closure to do it's own pass of DCE and yields generally better compression ratio (since static field references are warranted to be single-token).

Allowing reflection would require to structure the generation like
```js
(function () { "use strict";
function Test() { }
Test.main = Test_main;
function Test_main() {
console.log("Test.hx:3:","hi");
};
Test_main();
})();
```
which would let Closure to cull Test' declaration if it is not referenced directly.

Implementation-wise, may or may not be much trouble - while messing with CustomJSGenerator, I had a separate static path printer function to handle different modes, but I can't easily tell how things are in actual compiler.

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.