简体   繁体   English

如何强制Haxe宏返回类型为Array / Iterable?

[英]How to force Haxe macro return type to Array / Iterable?

I want to write a macro that returns an (expression of an) Array -- but I can't seem to convince the compiler that my returned value will be typed as an Array. 我想写一个返回(表达式)数组的宏 - 但我似乎无法说服编译器我的返回值将被键入为数组。 I always get "you can't iterate on a Dynamic value", even though I've tried: 我总是得到“你不能迭代动态值”,即使我尝试过:

  1. Explicitly typing the return as: ExprOf<Array<Whatever>> 显式键入返回ExprOf<Array<Whatever>>ExprOf<Array<Whatever>>
  2. Inserting a type hint in the output 在输出中插入类型提示

http://try-haxe.mrcdk.com/#D7D82 http://try-haxe.mrcdk.com/#D7D82

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

class Test {
  static function main() {
    trace("Haxe is great!");
    // ERROR: You can't iterate on a Dynamic value
    for (val in Macro.someArrayExpr()) {
      trace(val);
    }
  }
}

class Macro
{
  public static macro function someArrayExpr():ExprOf<Array<String>>
  {
    // Neither of these works:

    // Try to insert a type hint:
    // return Context.parse('([]:Array<String>)', Context.currentPos());

    return macro [];
  }
}

Uh oh, it looks like it's a side effect of defining my Macro class in the same module (file) as my invocation. 哦,看起来这是在我的调用中在同一模块(文件)中定义我的宏类的副作用。 Separating the classes into separate files makes it work! 将类分成单独的文件使其工作!

http://try-haxe.mrcdk.com/#57801 http://try-haxe.mrcdk.com/#57801

Test.hx: Test.hx:

class Test {
  static function main() {
    trace("Haxe is great!");
    // Hooray, it works!
    for (val in Macro.someArrayExpr()) {
      trace(val);
    }
  }
}

Macro.hx: Macro.hx:

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

//use this for macros or other classes
class Macro
{
  public static macro function someArrayExpr():ExprOf<Array<String>>
  {
    return macro ["a", "b", "c"];
  }
}

The technical explanation for this ( thanks to Juraj ): the Test class is being typed in the macro context. 对此的技术解释( 感谢Juraj ):Test类正在宏上下文中输入。 In that case, it's calling the macro from a macro, which is always typed Dynamic, hence the error. 在这种情况下,它从一个宏调用宏,它总是键入动态,因此错误。 So another solution is to exclude the class Test from being compiled into the macro context: http://try-haxe.mrcdk.com/#1f3b2 所以另一种解决方案是将类Test排除在编译到宏上下文之外: http//try-haxe.mrcdk.com/#1f3b2

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

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