在 ast 中替换术语名称的简单方法

easy way to replace term name in ast

我有以下代码:

@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 

这是一个简单的方法,但是如果我有一个包含很多表达式的大方法,替换变量名的最简单方法是什么(例如从 xy)?

经过一番调查,我需要使用Transfomer#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)