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

4
  • 1
    What did you try? What is not working? Indeed using metaprogramming features of Scala3 looks like the right direction. Commented Jun 30, 2021 at 17:32
  • This seems very similar to multi stage programming in Dotty or Squid, although it's more complex than simply having a String. Would a staging approach work better here? Commented Jul 4, 2021 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. Commented Jul 6, 2021 at 0:13
  • stackoverflow.com/questions/70945320/… Commented Sep 14, 2022 at 15:27

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.