Answer
The Haxe compiler resolves all #if, #elseif, #else and #endif directives during the parsing phase, before any macro expansion takes place. Nested blocks are evaluated depth‑first, left‑to‑right as they appear in the source file. The macro receives an AST that already reflects the pruned branches, so the order of nodes in the final AST is deterministic for a given set of -D flags.
Confirmed facts
- Conditional compilation is handled by the parser, not by the macro runner.
- Macros operate on the AST produced after
#if resolution. - Changing the
-D flags used to compile the macro class itself changes which branches are kept in the macro definition, which can affect the expanded AST.
Likely explanation
If you observe different AST outputs for the same source and flags, the most common cause is that the macro class is being compiled with a different set of defines than the main compilation unit. Because the macro’s own #if blocks are resolved when the macro class is compiled, a mismatch leads to different macro bodies and therefore different expanded code.
Steps to verify and enforce order
- Check the defines used when compiling the macro class (e.g., look at the build command or
haxelib run output). - Ensure the same
-D flags are passed to both the macro library and the project that uses it. - If you need conditional code inside a macro that depends on the caller’s defines, avoid
#if in the macro body and instead use haxe.macro.Context.getDefines() to query defines at expansion time and generate the appropriate AST. - As a workaround, move conditional logic out of the macro definition into parameters: pass the desired code fragments as
Expr arguments so the caller’s #if resolution happens before the macro sees them.
Missing diagnostic detail
Are you compiling the macro class with the exact same -D flags as the rest of your project? If not, that mismatch explains the non‑deterministic AST.
Verification
Run the compiler with -Dshow-defines (or inspect the build log) to confirm the active defines for both the macro library and the main source. Then compare the macro’s generated output with haxe --macro "MyMacro.test()" to see the AST after expansion.