Here my ugly copy paste from many examples from the web, I post it for future references.
macro public static function generateExtraMethods(nodeType:String):Array<Field> {
var code:String;
var exp:Array<Expr> = new Array();
switch (haxe.macro.Context.getType(nodeType))
{
case TInst(cl, _)://couldn't find another way to RTTI the class without an instance
code = "var _node:" + nodeType+" = new " + nodeType+"()"; //example: var node:MotionNode=new MotionNode();
exp.push(Context.parseInlineString(code, Context.currentPos()));
var array = cl.get().fields.get();
for (i in array)
{
code = "_node." +
i.name+" = cast(aEntity.get(" + i.type.getParameters()[0].toString() + ".ID)) ";
//example: node.position=cast(aEntitiy.get(Position.ID)); exp.push(Context.parseInlineString(code, Context.currentPos()));
}
code = "return _node"; //return node
exp.push(Context.parseInlineString(code, Context.currentPos()));
case _:
trace("Macro error wrong type, look at : " + Context.currentPos);
}
var c = macro : {
public function createNode(aEntity:Entity):PropertyNode{ //need to import Entity and PropertyNode in the class that use @build
$b { exp } //this turns the array into a single expr
}
}
switch (c) {
case TAnonymous(fields):
return Context.getBuildFields().concat(fields);
default:
throw 'unreachable';