1

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?

Baradé
  • 1,290
  • 1
  • 15
  • 35

1 Answers1

2

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

Dmytro Mitin
  • 48,194
  • 3
  • 28
  • 66
  • But will this work recursively for all Term.Name instances or only for the current tree which would mean that the top level tree must be a Term.Name? – Baradé Jul 22 '19 at 11:04
  • @Baradé Recursively. Top-level tree can be arbitrary. – Dmytro Mitin Jul 22 '19 at 11:46
  • If I use your example on a rather large Scala project I always end up getting a StackOverflowError. https://github.com/scalameta/scalameta/issues/1353 sounds like this is not getting fixed. Do I have to increase the stack size? – Baradé Jul 30 '19 at 13:30