romamik
romamik

Reputation: 595

Haxe: how to keep unused class from being eliminated

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.

Upvotes: 4

Views: 469

Answers (2)

Gama11
Gama11

Reputation: 34188

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.

Upvotes: 8

kLabz
kLabz

Reputation: 1827

@:keep and @:keepSub only keep classes. In your case, Foo has never been included in the compilation so the compiler has nothing to keep.

You can list more than one entry point for your application in your hxml (or in your haxe ... command) to include some classes: haxe -cp src -main MainFoo Foo --interp will find Foo. (more on --interp here: http://old.haxe.org/doc/compiler#macro-options)

You can also include a package and all its classes with --macro include('my.package') but in your example your classes are on the root package and I don't know if you can include this one.

More info on include: http://api.haxe.org/haxe/macro/Compiler.html#include

Upvotes: 6

Related Questions