Compiler Configuration with Macros
Macros can be used during the compilation process in order to generate custom code, but they can also be used to perform some pre-compilation tasks.
These compiler configuration macros can be used with the haxe --macro commandline parameter.
An example is to force the inclusion of all the files defined in a given package and its sub packages :
haxe --macro include('my.package') ....
Please use single-quotes for string constants since some OS (such as Windows) remove double-quotes.
The previous example is actually a shortcut for the following :
haxe --macro haxe.macro.Compiler.include('my.package') ....
And here's the code for the actual method :
public static function include( pack : String, ?rec = true ) { for( p in Context.getClassPath() ) { var p = p + pack.split(".").join("/"); if( !neko.FileSystem.exists(p) || !neko.FileSystem.isDirectory(p) ) continue; for( file in neko.FileSystem.readDirectory(p) ) { if( StringTools.endsWith(file, ".hx") ) { var cl = pack + "." + file.substr(0, file.length - 3); Context.getModule(cl); } else if( rec && neko.FileSystem.isDirectory(p + "/" + file) ) include(pack + "." + file, true, ignore); } } }
As you can see, there's no black magic going here. You can use any of the haxe.macro.Compiler methods or write your own custom versions.
So far the possibilities include :
- including files to make sure they are compiled
- excluding some classes from being generated
- patching types by removing some declared fields or changing their type
- adding metadata either before/class is defined or at end of compilation (with Context
onGeneratemethod) - defining a custom Javascript code generator (see below)
Much more possibilities will be added when there is a need for it.
Custom JS Generator
You can write your own custom JS generator in haXe : the generator will take care of creating the .js file(s) and generating the class structure/registration. You cannot however customize the way the haXe expressions are generated.
See haxe/std/haxe/macro/DefaultJSGenerator.hx as a reference implementation.
In order to use it, simply add the following commandline parameter to haxe compilation :
--macro haxe.macro.DefaultJSGenerator.use()