简体   繁体   English

如何使用 Haxe 宏构建摘要?

[英]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 .在这两种情况下,它们都会构建字段,这意味着它们必须返回一个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:修复示例中的编译器错误的最简单/最易读的方法是使用class 具体化,以便可以使用常规的 Haxe 语法声明构造函数:

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 {} {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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