Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading metadata in a Haxe macro

Tags:

macros

haxe

I would like to know how to read metadata from a class (and its methods) in a macro.

I tried to modify this example. I added : to see if metadata without them is only available in generated code, but nothing.. I have an empty result in all three cases.. Any ideas?

@:author("Nicolas")
@debug
class MyClass {
    @:range(1, 8)
    var value:Int;

    @broken
    @:noCompletion
    static function method() { }
}

class Boot {
    static public function main() {
        test();
    }

    macro public static function test() {
        trace(haxe.rtti.Meta.getType(MyClass)); // { author : ["Nicolas"], debug : null }
        trace(haxe.rtti.Meta.getFields(MyClass).value.range); // [1,8]
        trace(haxe.rtti.Meta.getStatics(MyClass).method); // { broken: null }
        return haxe.macro.Context.makeExpr({}, haxe.macro.Context.currentPos());
    }
}
like image 299
Peekmo Avatar asked Mar 31 '14 21:03

Peekmo


1 Answers

In order to access the types from a macro, you need to use the haxe.macro.* API rather than accessing haxe.rtti. The following example will trace both debug and author, which are the metadata applied to MyClass:

class Boot
{
  macro public static function test()
  {
    switch (haxe.macro.Context.getType("MyClass"))
    {
      case TInst(cl,_):
        trace(cl.get().meta.get());
      case _:
    }
  }
}

In order to get class field metadata, you must go through all fields from cl.get().fields.get().

See Context.getType(), ClassType and MetaAccess.

like image 167
Waneck Avatar answered Sep 19 '22 16:09

Waneck