Search code examples
scalascala-macrosscala-macro-paradise

easy way to replace term name in ast


I have the following code for:

@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"")
  }
}

Via this code, i want to replace variable name (x) in next example of usage:

@replace
def foo(x: Int) = x + 1 

it's simple method, but if i have a big method with many expression, what are the simpest way to replace variable name (from x to y for example)?


Solution

  • After some investigation, i need use Transfomer#transform method, some like this:

    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)