Search code examples
scalascalameta

How to replace all specific Term.Name expressions in an AST recursively with scalameta?


I would like to replace ALL occurences of specific Term.Name instances in the AST. Something like:

tree match {
    case t @ Term.Name(n) if (n == "bla") => Term.Apply(Term.Select(t, Term.Name("read")), List())
}

However, to achieve this, I will have to check for all different types of statements etc. and check inside these statements for the term. Is there any easier way with scalameta to replace all occurrences of a specific term?


Solution

  • Try to use Transformer

    import scala.meta._
    
    val transformer = new Transformer {
      override def apply(tree: Tree): Tree = tree match {
        case t @ Term.Name(n) if (n == "bla") => Term.Apply(Term.Select(t, Term.Name("read")), List())
        case node => super.apply(node)
      }
    }
    
    transformer(tree)
    

    https://scalameta.org/docs/trees/guide.html#custom-transformations