Scala 在ast中替换术语名的简单方法
我有以下代码:Scala 在ast中替换术语名的简单方法,scala,scala-macros,scala-macro-paradise,Scala,Scala Macros,Scala Macro Paradise,我有以下代码: @compileTimeOnly("enable macro paradise to expand macro annotations") class replace extends StaticAnnotation { def macroTransform(annottees: Any*) = macro replaceImpl.replace } object replaceImpl { def replace(c: Context)(annottees: c.Ex
@compileTimeOnly("enable macro paradise to expand macro annotations")
class replace extends StaticAnnotation {
def macroTransform(annottees: Any*) = macro replaceImpl.replace
}
object replaceImpl {
def replace(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
import c.universe._
// ?
c.Expr[Any](q"")
}
}
通过这段代码,我想在下一个用法示例中替换变量名(x
):
@replace
def foo(x: Int) = x + 1
这是一个简单的方法,但是如果我有一个包含许多表达式的大方法,那么用什么简单的方法来替换变量名(例如从
x
到y
)经过一些调查,我需要使用Transformer#transform
方法,一些类似这样的方法:
val t = new Transformer {
override def transform(tree: Tree) = {
val nt = tree match {
case Ident(x) => Ident(someNewName)
case x => x
}
super.transform(newTree)
}
}
// and then
val result = t.transform(inputTree)