HaxeDoc2

(やまだぃちぅ) #1

9.3.3 Class Reification


It is also possible to use reification to obtain an instance ofhaxe.macro.Expr.TypeDefinition.
This is indicated by themacro classsyntax as shown here:
1 class Main {
2 macro static function
3 generateClass(funcName:String){
4 var c = macro class MyClass {
5 public function new() { }
6 public function $funcName() {
7 trace($v{funcName}+" wascalled");
8 }
9 }
10 haxe.macro.Context.defineType(c);
11 return macro new MyClass();
12 }
13
14 public static function main() {
15 var c = generateClass("myFunc");
16 c.myFunc();
17 }
18 }


The generatedTypeDefinitioninstance is typically passed tohaxe.macro.Context.defineType
in order to add a new type to the calling context (not the macro context itself).
This kind of reification can also be useful to obtain instances ofhaxe.macro.Expr.Field,
which are available from thefieldsarray of the generatedTypeDefinition.

9.4 Tools


The Haxe Standard Library comes with a set of tool-classes to simplify working with macros.
These classes work best as static extensions (6.3) and can be brought into context either individ-
ually or as a whole throughusing haxe.macro.Tools. These classes are:

ComplexTypeTools:Allows printingComplexTypeinstances in a human-readable way. Also
allows determining theTypecorresponding to aComplexType.

ExprTools:Allows printingExprinstances in a human-readable way. Also allows iterating
and mapping expressions.

MacroStringTools:Offers useful operations on strings and string expressions in macro con-
text.

TypeTools:Allows printingTypeinstances in a human-readable way. Also offers several
useful operations on types, such as unifying (3.5) them or getting their corresponding
ComplexType.

Trivia: The tinkerbell library and why Tools.hx works
We learned about static extensions that using amoduleimplies that all its types are brought
into static extension context. As it turns out, such a type can also be a typedef (3.1) to another
type. The compiler then considers this type part of the module, and extends static extension
Free download pdf