My goal is to get Scala 3 code as a String and to parse it into Abstract Syntax Tree for Scala 3 at runtime. In the process if the code has compilation errors, I should get that as part of some exception. The larger goal is to end up with Expr[T] if the scala code is valid and execute it by splicing in the right bits(I have this part covered).
This was doable in Scala 2.* using scala-reflect here.
val source =
"""
|object HelloWorld {
| def main(args: Array[String]): Unit = {
| println("Hello, world!")
| }
|}
|
|HelloWorld.main(Array())
|""".stripMargin
val tree = toolbox.parse(source)
val binary = toolbox.compile(tree)
binary()
But as far as I can surmise, in Scala 3, scala-reflect will not be ported. How could I achieve the same in Scala 3?
Some relevant links here and here
Ohh, you can look at ammonite: parser: https://github.com/com-lihaoyi/Ammonite/blob/master/amm/compiler/src/main/scala-3/ammonite/compiler/Parsers.scala (They create a virtual file and run a compiler on it).
If you don't want evaluation but just AST, then maybe scalameta [https://scalameta.org/] will be enough. As I know, scala3 syntax is supported in the latest version, but scalameta itself (i.e. processing of parsed tree) is on scala2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With