在宏中创建函数

Creating a function in a macro

我正在尝试使用 @:build@:autoBuild 宏向 class 及其子 classes 的所有实例添加静态变量和静态函数.

我设法让静态变量工作,但我不知道如何 "build" 来自各种 EFunctionEFor 等的函数

这是我目前的代码:

macro static public function addGetId() :Array<Field>
{
    var fields : Array<Field> = Context.getBuildFields();

    // The static _id field
    var idField = {
        name : "_id",
        doc : null,
        meta : [],
        access : [AStatic, APrivate],
        kind : FVar(macro : Int, macro -1),
        pos : Context.currentPos()
    };

    // The getId function field
    var getIdField = {
        name : "getId",
        doc : "Returns the ID of this command type.",
        meta : [],
        access : [AStatic, APublic],
        kind : FFun({
            params : [],
            args : [],
            expr: // What do I have to write here???
            ret : macro : Int
        }),
        pos : Context.currentPos()
    };

    fields.push(idField);
    fields.push(getIdField);
    return fields;
}

这是我要添加的函数在正常代码中的样子,如果它实际上在 .hx 文件中:

public static function getId() : Int
{
    if (_id == -1)
    {
        _id = MySingleton.getInst().myGreatFunction()
    }
    return _id;
};

所以它引用了新添加的 _id 变量以及一些单例 class 函数。
那么:完整的 getIdField() 会是什么样子?

加分题:
我最大的问题是完全没有关于这些功能的文档以及手册中的任何有用示例。有没有真正有用的教程来创建这样的函数?

奖金奖金问题:
FFun中的paramsargs有什么区别?

您可以使用 reification 编写函数体,就像在常规 Haxe 代码中一样:

expr: macro {
    if (_id == -1) {
        _id = 0;
    }
    return _id;
},

params 是类型参数列表,args 是函数接收的参数列表。关于这个 on the Haxe Manual:

有一个琐事部分

Trivia: Argument vs. Parameter

In some other programming languages, argument and parameter are used interchangeably. In Haxe, argument is used when referring to methods and parameter refers to Type Parameters.