A curated list of articles, examples, and other resources for the Haxe macro system.
In Haxe, macros are preprocessor functions included in source code which transform and generate syntax during compilation. They do not preprocess the raw text of the source code, but rather directly edit the internal abstract syntax tree (AST) of the compiler. As the [manual] (https://haxe.org/manual/macro.html) describes them:
A basic macro is a syntax-transformation. It receives zero or more expressions and also returns an expression. If a macro is called, it effectively inserts code at the place it was called from. In that respect, it could be compared to a preprocessor like
#definein C++, but a Haxe macro is not a textual replacement tool.
- The Haxe macro manual
- Macro examples in the Code Cookbook
- Expr API -
Expris the fundamental building block of all Haxe code. Any Haxe source code can, and is, represented by an instance of theExprobject. Macros take inExprobjects and outputExprobjects. Understanding the structure of anExprinstance, how to parse them and pattern match them, and how to construct them, is 90% of macro development. - Context API - Critical class providing contextual information about the current state of the AST, exposes callback hooks for the compiler, defines new types, and other utility functions. Look over it to get a good scope of what is possible.
- Compiler API - Another static utility class with more emphasis on changing compiler functions rather than editing the AST. Has some of the most powerful, most esoteric functions.
- Various standard macro tools:
-
deepnightLibs Cinematic.hx - Builds an elegant orchestrator/coroutine system, effectively extends the language by parsing expressions in a bespoke form like
{doStuff() > wait(500)}. Showcases how operators like>can be co-opted for creative uses. -
compiletime - Access compile-time information not normally available during runtime, such as lists of all defined types, all types implementing a certain interface, etc.
-
heaps Res.hx system - In the
./res/folder of your source code, provides a static class which reads the folder and adds typed fields for each with full IDE completion. Effectively statically types resource files and gives them IntelliSense. -
haxeui - An incredibly impressive system in many ways, the consummate showcase of all Haxe's unique functions. Exposes build macros to load XML markup files into classes, effectively implementing a sort of pseudo-MVVM system. Not even mentioning all the internal uses of macros which are used to make behaviors composite.
Definitely a lot still missing, I am just updating this as I remember or encounter different things. If you want to add to this list, raise a PR or contact me directly. Especially looking for how-to guides, gists, concise examples or unique, creative examples.