Reading metadata in a Haxe macro
Asked Answered
R

1

6

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());
    }
}
Rounders answered 31/3, 2014 at 21:21 Comment(0)
H
6

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.

Hanschen answered 2/4, 2014 at 4:4 Comment(2)
Pretty new to this, but could you elaborate where the cl and _ comes from? (ex: in case TInst(cl,_): and case _:)Fillip
@bigp have a look at the pattern matching documentation ( at haxe.org/manual/lf-pattern-matching.html )Hanschen

© 2022 - 2024 — McMap. All rights reserved.