Macros 获取Haxe宏中对象的类型

Macros 获取Haxe宏中对象的类型,macros,haxe,Macros,Haxe,我希望在宏中获取对象的类,以便访问其静态变量: // 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

我希望在宏中获取对象的类,以便访问其静态变量:

// 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);
  }
}
预期用途:

var c = new Container();
c.add(new Child1());
c.add(new Child2());
您可以使用获取表达式的类型,然后需要进行一些模式匹配以找出类型的名称。以下仅适用于类,因为它仅匹配
TInst
,但可以扩展:

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);
    }
}
这将生成以下代码:

var c = new Container();
c.addChild(Child1.id_, new Child1());
c.addChild(Child2.id_, new Child2());
请注意,通过其非限定名称访问
\u id
仅在实际导入(或顶级)时才是安全的-实际上,您希望结合使用
t.pack
生成完全限定路径