说我有一个表达式,我想捕获它的树(不求值!),然后稍后再将其传递给另一个宏:
// capture a tree from some arbitrary expression
val capturedTree = captureMacro( some(expression(tree())) )
// plug the tree into here
val result = processMacro(capturedTree, otherStuff)
有没有办法做到这一点?我尝试过将capturedTree
制成精致的类型,希望能保留最初的树,但那没有发生:
trait WithCapturedTree { def tree:Any }
class ReturnTreeMacro(val c:MacroContext) {
import c.universe._
def run(expression: Tree) =
q"new WithCapturedTree {val tree = ${expression}}"
}
def returnTree(expression:String):WithCapturedTree = macro ReturnTreeMacro.run
reify { returnTree("foo"+"bar") }
// returns Expr[WithCapturedTree{val tree: java.lang.String}](returnTree("foobar"))
// I.e. the result of "foo"+"bar" has already been evaluated!
有没有办法使这种方法起作用?有更好的解决方案吗?