Search code examples
haxedead-code

How to prevent dead-code removal of utility libraries in Haxe?


I've been tasked with creating conformance tests of user input, the task if fairly tricky and we need very high levels of reliability. The server runs on PHP, the client runs on JS, and I thought Haxe might reduce duplicative work.

However, I'm having trouble with deadcode removal. Since I am just creating helper functions (utilObject.isMeaningOfLife(42)) I don't have a main program that calls each one. I tried adding @:keep: to a utility class, but it was cut out anyway.

I tried to specify that utility class through the -main switch, but I had to add a dummy main() method and this doesn't scale beyond that single class.


Solution

  • You can force the inclusion of all the files defined in a given package and its sub packages to be included in the build using a compiler argument.

    haxe --macro include('my.package') ..etc

    This is a shortcut to the macro.Compiler.include function. As you can see the signature of this function allows you to do it recursive and also exclude packages.

    static include (pack:String, rec:Bool = true, ?ignore:Array<String>, ?classPaths:Array<String>):Void
    

    I think you don't have to use @:keep in that case for each library class.

    I'm not sure if this is what you are looking for, I hope it helps. Otherwise this could be helpful checks:

    • Is it bad that the code is cut away if you don't use it?
    • It could also be the case some code is inlined in the final output?
    • Compile your code using the compiler flag -dce std as mentioned in comments.
    • If you use the static analyzer, don't use it.
    • Add @:keep and reference the class+function somewhere.
    • Otherwise provide minimal setup if you can reproduce.