Skip to content
This repository has been archived by the owner on May 30, 2023. It is now read-only.

Tasty Reflection: Tree Traversal #3

Open
anatoliykmetyuk opened this issue Jul 2, 2019 · 0 comments
Open

Tasty Reflection: Tree Traversal #3

anatoliykmetyuk opened this issue Jul 2, 2019 · 0 comments
Labels
intent:add-knowledge You have learnt something while working on the Dotty compiler and you want to preserve this info

Comments

@anatoliykmetyuk
Copy link
Contributor

// How to use TreeAccumulator with Unit
val acc = new TreeAccumulator[Unit] {
  def foldTree(x: Unit, tree: Tree)(implicit ctx: Context): Unit = {
    println(s"Tree ${tree.show}")
    foldOverTree(x, tree)
  }
  def foldPattern(x: Unit, tree: Pattern)(implicit ctx: Context): Unit = {
    println(s"Pattren ${tree.show}")
    foldOverPattern(x, tree)
  }
}
acc.foldTree((), tree)

// Equivalent of the above code
val trs = new TreeTraverser {
  override def traverseTree(tree: Tree)(implicit ctx: Context): Unit = {
    println(s"Tree ${tree.show}")
    traverseTreeChildren(tree)
  }

  override def traversePattern(tree: Pattern)(implicit ctx: Context): Unit = {
    println(s"Pattern ${tree.show}")
    traversePatternChildren(tree)
  }
}
trs.traverseTree(tree)

// How to replace the RHS of a variable called "name" to String "Dog"
val map = new TreeMap {
  override def transformStatement(tree: Statement)(implicit ctx: Context): Statement = {
    def localCtx(definition: Definition): Context = definition.symbol.localContext
    tree match {
      case IsValDef(tree) =>
        implicit val ctx = localCtx(tree)
        val tpt1 = transformTypeTree(tree.tpt)
        val rhs1 = tree.rhs.map { x =>
          if (tree.name == "name") Literal(Constant.String("Dog")) else transformTerm(x)
        }
        ValDef.copy(tree)(tree.name, tpt1, rhs1)
      case _ => super.transformStatement(tree)
    }
  }
}
map.transformTerm(tree.underlyingArgument).seal

Usage:

f {
  println("Hello World")
  val name = "Cat"
  println(s"I said hello world, $name")
}

Where f is the macro doing the transformations above.

@anatoliykmetyuk anatoliykmetyuk added the intent:add-knowledge You have learnt something while working on the Dotty compiler and you want to preserve this info label Jul 2, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
intent:add-knowledge You have learnt something while working on the Dotty compiler and you want to preserve this info
Projects
None yet
Development

No branches or pull requests

1 participant