简体   繁体   中英

How to build an abstract with a Haxe macro?

I couldn't find any example code or tutorial floating around that creates abstracts with macros.

//Class code ReflectionClassInfo.hx
@:build(ReflectionClassInfoMacro.build())
abstract ReflectionClassInfo({}) from ({}) to ({}) {}

//Driver code
var r=new ReflectionClassInfo();
//Immeditately makes the compiler complain about there is no constructor

How can I fix the compiler error?

One thing that's important to realize is that there isn't really any difference between build macros for classes and abstracts. In both cases, they build fields, meaning that they have to return an array of haxe.macro.Expr.Field . So any documentation or code example that applies to one also applies to the other.

The easiest / most readable way to fix the compiler error in your example is by using class reification , so that the constructor can be declared with regular Haxe syntax:

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

class Macro {
    public static function build():Array<Field> {
        var fields = Context.getBuildFields();
        fields = fields.concat((macro class {
            public function new() {
                this = {};
            }
        }).fields);
        return fields;
    }
}
class Main {
    static function main() {
        new Abstract(); // compiles
    }
}

@:build(Macro.build())
abstract Abstract({}) from {} to {} {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM