[英]Is it possible to capture some value for use inside of `splice` part of `reify` macro?
For example, I have some list and want to iterate on it, and do macro transformation on each value: 例如,我有一些列表,想要对其进行迭代,并对每个值进行宏转换:
reify {
someIntListExpr.splice.foreach { i =>
// transform is a macro of the form 'transform(c: Context)(i: c.Expr[Int]): c.Expr[Unit]
transform(i).splice
}
}
But the compiler spits out error message: 但是编译器吐出错误消息:
found: Int
required: c.universe.Expr[Int]
Is there a way to fix it? 有办法解决吗?
In simple cases this will do the trick: 在简单的情况下,这可以解决问题:
someIntListExpr.splice.foreach { i =>
transformImpl(c)(c.Expr[Int](Ident(newTermName("i")))).splice
}
Alternatively you can create method like this 或者,您可以创建这样的方法
def trans(i: Int): Unit = macro transform
and apply it: 并应用:
reify {
someIntListExpr.splice.foreach { i =>
trans(i)
}
}
Sometimes you can actually get List[c.Expr[Unit]]
. 有时您实际上可以得到List[c.Expr[Unit]]
。
If your method ( def myMethod(l: List[Int]): unti = macro myMethodImpl
) is called like myMethod(List(1, 2, x))
then you can get List[c.Expr[Unit]]
: 如果像myMethod(List(1, 2, x))
那样调用您的方法( def myMethod(l: List[Int]): unti = macro myMethodImpl
) myMethod(List(1, 2, x))
则可以获取List[c.Expr[Unit]]
:
def myMethodImpl(c: Context)(l: c.Expr[List[Int]]): ... = {
import c.universe.Apply
val es = l match {
case Apply(_, l: List[c.Expr[Int]]) => l
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.