Search code examples
scalacompiler-constructionprogramming-languagescompilationabstract-syntax-tree

How to interact with the compiler in Scala code itself?


I wonder how many ways exist to interact with the Scala compiler outside of the normal “invoke it on the command line to compile my sources”.

Is there is some way to parse code, build an abstract syntax tree or use a library to compile code at runtime?


Solution

  • Some time ago I used the (now depricated) scala.tools.nsc.Interpreter class to load, modify and -- surprise! -- interpret Scala code at runtime. If you want to exchange values between your and the interpreted code have a look at its bind method. It also has a compileSources and a compileString method but I didn't used one of them so far. Also I don't know anything about how to use this (or something else) to get the AST.

    See also: What is the purpose of the scala.tools.nsc package? and the nsc package scaladoc.

    Update: This should answer the AST question (from 2009, could be outdated): Scala AST in Scala