Haxe: Running @:build macro on typedefs

As at 3.2.1, Haxe does not support @:build macros over a typedef. But I just discovered a trick to do that. That utilizes a @:genericBuild macro. Well, honestly, this is not truly a build macro because the type is read-only. i.e. you can’t add or remove or alter fields of the original type. But you can declare a new type based on that and return it as the type for the call site. I found it quite useful for my use case because I would like to make a copy of the typedef in some fashion.

@:build(Macro.build()) // this doesn't work
typedef MyType = {}

@:genericBuild(Macro.build()) // the trick is here
class Wrapper<T> {}

In Macro.hx:

public static function build() {
    var ret = null;

    var type = switch Context.getLocalType() {
        case TInst(_, [param]):
            // here the `param` is MyType, store it and return it
            // at the end of the macro
            // so that `var t:Wrapper<MyType>` is actually 
            // equivalent to `var t:MyType`
            param;

        default:
            throw 'Invalid Wrapper';
    }

    // at this point, do whatever you need with `MyType`, 
    // as if a build macro is running on it

    return type; // return it at last
}

Leave a Reply

Your email address will not be published. Required fields are marked *