HaxeDoc2

(やまだぃちぅ) #1
accordingly.
This “trick” was first used in Juraj Kirchheim’stinkerbell^1 library for exactly the same pur-
pose. Tinkerbell provided many useful macro tools long before they made it into the Haxe
Compiler and Haxe Standard Library. It remains the primary library for additional macro
tools and offers other useful functionality as well.

9.5 Type Building


Type-building macros are different from expression macros in several ways:


  • They do not return expressions, but an array of class fields. Their return type must be set
    explicitly toArray<haxe.macro.Expr.Field>.

  • Their context (9.1) has no local method and no local variables.

  • Their context does have build fields, available fromhaxe.macro.Context.getBuildFields().

  • They are not called directly, but are argument to a@:buildor@:autoBuildmetadata
    (6.9) on a class (2.3) or enum (2.4) declaration.


The following example demonstrates type building. Note that it is split up into two files
for a reason: If a module contains amacrofunction, it has to be typed into macro context as
well. This is often a problem for type-building macros because the type to be built could only
be loaded in its incomplete state, before the building macro has run. We recommend to always
define type-building macros in their own module.
1 import haxe.macro.Context;
2 import haxe.macro.Expr;
3
4 class TypeBuildingMacro {
5 macro static public function
6 build(fieldName:String):Array{
7 var fields = Context.getBuildFields();
8 var newField ={
9 name: fieldName,
10 doc: null,
11 meta: [],
12 access:[AStatic, APublic],
13 kind: FVar(macro : String,
14 macro "my default"),
15 pos: Context.currentPos()
16 };
17 fields.push(newField);
18 return fields;
19 }
20 }


1 @:build(TypeBuildingMacro.build("myFunc"))
2 class Main {
3 static public function main() {
4 trace(Main.myFunc); // my default
Free download pdf