Get Object Type in Haxe Macro

I would like to get the class of the object in the macro so that I can access its static variables:

// autoBuild macro adds static field "id_ : Int" to all subclasses
class Base {

}

class Child1 extends Base {
  public function new() {}
}

class Child2 extends Base {
  public function new() {}
}

class Container {
  public function addChild(index: Int, object: Base) {}

  macro function add(object: ???) {
    // find out class of on object
    // ???
    // var id = class.id_;
    this.addChild(id, object);
  }
}

Desired Usage:

var c = new Container();
c.add(new Child1());
c.add(new Child2());
+5
source share
1 answer

You can use Context.typeof()to get the type of expression - then you need to run several patterns to find out the type name. The following only works with classes, since it only matches TInst, but can be extended:

import haxe.macro.Context;
import haxe.macro.Expr;

class Container {
    // [...]

    public macro function add(self:Expr, object:Expr):Expr {
        var name = switch (Context.typeof(object)) {
            case TInst(_.get() => t, _): t.name;
            case _: throw "object type not found";
        }
        return macro $self.addChild($i{name}.id_, $object);
    }
}

This will lead to the creation of the following code:

var c = new Container();
c.addChild(Child1.id_, new Child1());
c.addChild(Child2.id_, new Child2());

, _id , ( ) - t.pack $p{}, .

+3

Source: https://habr.com/ru/post/1681143/


All Articles