9

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

arinray
  • 178
  • 1
  • 12
  • 1
    What did you try? What is not working? Indeed using metaprogramming features of Scala3 looks like the right direction. – Gaël J Jun 30 '21 at 17:32
  • This seems very similar to multi stage programming in [Dotty](http://dotty.epfl.ch/docs/reference/metaprogramming/staging.html) or [Squid](https://epfldata.github.io/squid/tutorial/2-staging.html), although it's more complex than simply having a String. Would a staging approach work better here? – Will Sargent Jul 04 '21 at 21:31
  • @WillSargent Yes I saw that but did not figure out a way to go from a string to quotes and splices at runtime. My code as string could come in at runtime, namely via a REST request. – arinray Jul 06 '21 at 00:13
  • https://stackoverflow.com/questions/70945320/how-to-compile-and-execute-scala-code-at-run-time-in-scala3 – Dmytro Mitin Sep 14 '22 at 15:27

1 Answers1

3

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.

rssh
  • 464
  • 4
  • 5