9.7 Persistent Variables

When using macros in combination with the completion server, certain values obtained in a build or initialization macro can be retained for the next time the macro is executed. This is useful if obtaining the values is resource-intensive, or if the macro needs to keep track of previous builds. To mark a static field as persistent across macro builds, it should be annotated with the :persistent metadata.

As an example, here is Welcome.hx:

import haxe.macro.Expr;

class Welcome {
  @:persistent static var firstBuild:Bool = true;

  public static build():Array<Field> {
    if (firstBuild) {
      trace("congratulations on your first build!");
      firstBuild = false;
    }
    return null;
  }
}

And Main.hx:

@:build(Welcome.build())
class Main {
  public static function main() {}
}

After starting the completion server with haxe --wait 6000, we perform a build with haxe --connect 6000 --main Main --no-output. The first time the congratulatory message is printed during compilation. If we execute the same command again, however, it is not - the firstBuild variable retains the value false from the previous build.