简体   繁体   English

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

[英]In Haxe, how do you read a variable name inside of a Macro?

I'm trying to use Macros to convert some variable declarations from this: 我正在尝试使用宏从此转换一些变量声明:

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

... to this: ...对此:

function test() {
    var someComp:Component = cast container.getCompById("someComp");
}

I'm leaning more toward the 3rd option (shorter syntax, same results). 我更倾向于第三个选项(较短的语法,相同的结果)。

But I have no idea how to write the macro (should it take a String as parameter? An expression?) and how to properly return that as a macro expression. 但是我不知道如何编写宏(是否应该将String作为参数?表达式?)以及如何正确地将其作为宏表达式返回。

This is the (broken) code I've got so far: 这是到目前为止我得到的(中断)代码:

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

Any ideas? 有任何想法吗?

The issue with the code you posted is first that you'd need reification escaping mechanisms for this to work correctly - so the first change would be to use the macro escapes: 您发布的代码的问题首先是,您需要使用转义转义机制才能使其正常工作-因此,第一个更改是使用宏转义:

return macro var $someVar:$typeVar = cast container.getCompById($v{someVar});

Now there will be some problems with this: It's expecting someVar to be of type String, and typeVar to be of type ComplexType . 现在会有一些问题:期望someVar的类型为String,而typeVar的类型为ComplexType It's easy to get the string component from an Expr . Expr获取字符串组件很容易。 It's not so easy however to transform an Expr into ComplexType . 然而,将Expr转换为ComplexType非易事。 The easiest way to do that is to use the tink_macros library and use asComplexType 最简单的方法是使用tink_macros库并使用asComplexType

So the (untested) code will look something like: 因此,(未经测试的)代码将类似于:

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

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

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