Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haxe: how to keep unused class from being eliminated

Tags:

haxe

I have classes that are never directly mentioned in other code, but only accessed using Type.resolveClass. I want them to be compiled and included in the app, but I can't get how to do this. I thought that @:keep (or @:keepSub) is exactly for this, but it does not work as I expected. This is what I do:

Main.hx:

package;
//import Foo; //uncomment this line to make it work
class Main {
    static function main() trace(Type.resolveClass('Foo'));
}

Foo.hx:

package;
@:keep class Foo {}

But this traces null (I've tested JS and Flash) Even if I compile with -dce no it still traces null.

Not sure if it's a compiler issue or I do not understand how it works.

like image 344
romamik Avatar asked Dec 08 '22 19:12

romamik


1 Answers

This is not a compiler issue, it's correct behavior. If a module is never imported, it is never included in compilation to begin with. The compiler never gets to see the @:keep.

A common workaround for this is to use --macro include('package') (see Compiler.include()), which forces all modules in package to be compiled.

Note that a wildcard import (import package.*;) won't work, since wildcard imports are lazy:

When using wildcard imports on a package the compiler does not eagerly process all modules in that package. This means that these modules are never actually seen by the compiler unless used explicitly and are then not part of the generated output.

like image 172
Gama11 Avatar answered Apr 02 '23 01:04

Gama11