Creating Scala Code Trees from a Scala Compiler Plugin

There are several resources on the web that are instructive in writing Scala compiler plugins that match a template with code, but they do not help generate code (building symbol trees). Where should I start figuring out how to do this? (If there is an easier way than manually creating symbol trees, I would be interested as well.)

For example, I would like to write a plugin that replaces some code with a simple AST for this expression, where the variables (extracted from the source code) can be of any type:

"" + hello + ", " + world + "!" 

I understand that this can be tricky due to boxing and toString , for example. if hello were an object and world were int, it really should be something like:

 "".+(hello.toString().+(", ".+(new Integer(world).toString().+("!")))) 
+7
compiler-construction scala plugins code-generation
source share
3 answers

If you generate a tree before the erasure phase, you can enter hello and world with Any and call toString on them.

  ~: cat test.scala object test { def f(hello: Any, world: Any) = "" + hello + ", " + world + "!" f("1", "2") f(1, 1) } ~: scalac -Xprint:typer test.scala [[syntax trees at end of typer]]// Scala source: test.scala package <empty> { final object test extends java.lang.Object with ScalaObject { def this(): object test = { test.super.this(); () }; def f(hello: Any, world: Any): java.lang.String = "".+(hello).+(", ").+(world).+("!"); test.this.f("1", "2"); test.this.f(1, 1) } } ~: scalac -Xprint:erasure test.scala [[syntax trees at end of erasure]]// Scala source: test.scala package <empty> { final class test extends java.lang.Object with ScalaObject { def this(): object test = { test.super.this(); () }; def f(hello: java.lang.Object, world: java.lang.Object): java.lang.String = "".+(hello).+(", ").+(world).+("!"); test.this.f("1", "2"); test.this.f(scala.Int.box(1), scala.Int.box(1)) } } 
+3
source share

you can find something in this project: http://github.com/scala-incubator/autoproxy-plugin

+2
source share

This thread looks relevant: Convert Scala AST to source code

In particular, you can build a Scala AST with the specified TreeDSL . http://www.scala-lang.org/archives/downloads/distrib/files/nightly/docs/compiler/scala/tools/nsc/ast/TreeDSL.html

+1
source share

All Articles