在 scala 中,是否可以将函数定义为具有传递 AST 参数,以便函数的输入 AST 可以按原样传递给宏?
In scala, can a function be defined to have pass-by-AST parameter, such that the input AST of a function can be passed to a macro as-is?
我将以 shapeless 库为例:
import shapeless.test.illTyped
假设我想将 illType
函数包装在另一个函数中,我尝试了两种不同的方法来做到这一点:
(按值)
def shouldTypeError(v: String) = illTyped(v, ".*")
[ERROR] ... : exception during macro expansion:
scala.MatchError: v (of class scala.reflect.internal.Trees$Ident)
at shapeless.test.IllTypedMacros.applyImpl(typechecking.scala:43)
(按姓名)
def shouldTypeError(v: => String) = illTyped(v, ".*")
[ERROR ... ]: exception during macro expansion:
scala.MatchError: v (of class scala.reflect.internal.Trees$Ident)
at shapeless.test.IllTypedMacros.applyImpl(typechecking.scala:43)
所以 none 它们按预期工作。在最新的 scala 或 dotty 中这可能吗?
没有。外部函数也必须是宏
def shouldTypeError(v: String): Unit = macro shouldTypeErrorImpl
def shouldTypeErrorImpl(c: blackbox.Context)(v: c.Tree): c.Tree = {
import c.universe._
q"""_root_.shapeless.test.illTyped($v, ".*")"""
}
我将以 shapeless 库为例:
import shapeless.test.illTyped
假设我想将 illType
函数包装在另一个函数中,我尝试了两种不同的方法来做到这一点:
(按值)
def shouldTypeError(v: String) = illTyped(v, ".*")
[ERROR] ... : exception during macro expansion:
scala.MatchError: v (of class scala.reflect.internal.Trees$Ident)
at shapeless.test.IllTypedMacros.applyImpl(typechecking.scala:43)
(按姓名)
def shouldTypeError(v: => String) = illTyped(v, ".*")
[ERROR ... ]: exception during macro expansion:
scala.MatchError: v (of class scala.reflect.internal.Trees$Ident)
at shapeless.test.IllTypedMacros.applyImpl(typechecking.scala:43)
所以 none 它们按预期工作。在最新的 scala 或 dotty 中这可能吗?
没有。外部函数也必须是宏
def shouldTypeError(v: String): Unit = macro shouldTypeErrorImpl
def shouldTypeErrorImpl(c: blackbox.Context)(v: c.Tree): c.Tree = {
import c.universe._
q"""_root_.shapeless.test.illTyped($v, ".*")"""
}