5 }
6 }
Thebuildmethod ofTestBuildingMacroperforms three steps:1.It obtains the build fields usingContext.getBuildFields().2.It declares a newhaxe.macro.expr.Fieldfield using thefuncNamemacro argument
as field name. This field is aStringvariable (4.1) with a default value"my default"
(from thekindfield) and is public and static (from theaccessfield).3.It adds the new field to the build field array and returns it.This macro is argument to the@:buildmetadata on theMainclass. As soon as this type is
required, the compiler does the following:1.It parses the module file, including the class fields.2.It sets up the type, including its relation to other types through inheritance (2.3.2) and
interfaces (2.3.3).3.It executes the type-building macro according to the@:buildmetadata.4.It continues typing the class normally with the fields returned by the type-building macro.This allows adding and modifying class fields at will in a type-building macro. In our exam-
ple, the macro is called with a"myFunc"argument, makingMain.myFunca valid field access.
If a type-building macro should not modify anything, the macro can returnnull. This indi-
cates to the compiler that no changes are intended and is preferable to returningContext.getBuildFields().9.5.1 Enum building
Building enums (2.4) is analogous to building classes with a simple mapping:- Enum constructors without arguments are variable fieldsFVar.
- Enum constructors with arguments are method fieldsFFun.
Check if we can build
GADTs this way.
Check if we can build
GADTs this way. 1 import haxe.macro.Context;
2 import haxe.macro.Expr;
3
4 class EnumBuildingMacro {
5 macro static public function
6 build():Array<Field>{
7 var noArgs =
8 makeEnumField("A", FVar(null, null));
9 var eFunc = macro function(value:Int) { };
10 var fInt = switch (eFunc.expr){
11 case EFunction(_,f): f;
12 case _: throw "false";
13 }
14 var intArg =
15 makeEnumField("B", FFun(fInt));
16 return [noArgs, intArg];