在Haxe中,如何读取宏内的变量名?

big*_*igp 2 macros haxe local-variables compile-time

我正在尝试使用宏来转换一些变量声明:

function test():Void {
    var someComp:Component = __SOME_MACRO__();

    // Or...
    @getCompById var someComp:Component;

    // Or even simpler...
    getCompById(someComp, Component); //do some fancy macro magic...
    // Also, if it's not possible/easy with a variable ...
    getCompById("someComp", Component); //with a string of the variable name.
}
Run Code Online (Sandbox Code Playgroud)

......对此:

function test() {
    var someComp:Component = cast container.getCompById("someComp");
}
Run Code Online (Sandbox Code Playgroud)

我更倾向于第三种选择(语法更短,结果相同).

但是我不知道如何编写宏(它应该将String作为参数吗?表达式?)以及如何正确地将其作为宏表达式返回.

这是我到目前为止的(破碎)代码:

macro static function getCompById(someVar:Expr, typeVar:Expr) {
    return macro {
        var someVar:typeVar = cast container.getCompById("someVar");
    };
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Wan*_*eck 5

你发布的代码的问题首先是你需要reification转义机制才能正常工作 - 所以第一个改变就是使用宏转义:

return macro var $someVar:$typeVar = cast container.getCompById($v{someVar});
Run Code Online (Sandbox Code Playgroud)

现在会出现一些问题:它期望someVar是String类型,并且typeVarComplexType类型.从中获取字符串组件很容易Expr.然而,变换Expr成一个并不容易ComplexType.最简单的方法是使用tink_macros库并使用asComplexType

所以(未经测试的)代码看起来像:

using tink.MacroAPI;
using haxe.macro.Tools;
macro static function getCompById(someVarExpr:Expr, typeVarExpr:Expr)
{
  var typeVar = typeVarExpr.toString().asComplexType();
  switch (someVarExpr.getIdent())
  {
    case Success(someVar):
      return macro var $someVar:$typeVar = cast container.getCompById($v{someVar});
    case Failure(error): throw error;
  }
}
Run Code Online (Sandbox Code Playgroud)