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?
In computer programming, self-hosting is the use of a program as part of the toolchain or operating system that produces new versions of that same program—for example, a compiler that can compile its own source code.
Scala has both a compiler and an interpreter which can execute Scala code. The Scala compiler compiles your Scala code into Java Byte Code which can then be executed by the scala command. The scala command is similar to the java command, in that it executes your compiled Scala code.
To compile the code, type "scalac hello_world. scala" and press enter.
Scala Native is a Scala compiler that targets the LLVM compiler infrastructure to create executable code that uses a lightweight managed runtime, which uses the Boehm garbage collector.
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
I have done this in the past by creating a new CompilerCommand instance to parse command line arguments and, more importantly, by extending the ever-terrifying Global class.
By overriding the computeInternalPhases
method, you can use only some phases of the compiler (e.g. up to refchecks
, to use it as a parser/typechecker only), and you can add your own phases (plugins) as you would expect. You can of course also go all the way to generating class files.
So yes, it is definitely possible. After all, the compiler itself also runs on the JVM.
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