This demo demonstrates how to build a native executable version of the Scala compiler.
-
First, make sure that the environment variables
SCALA_HOME
points to Scala 2.12.x. Check whatscala
you have on your system by running:echo $SCALA_HOME scala --version
-
Download and install the latest GraalVM JDK with Native Image using the GraalVM JDK Downloader:
bash <(curl -sL https://get.graalvm.org/jdk)
-
Download or clone the repository and navigate into the
scala-examples/scalac-native
directory:git clone https://github.com/graalvm/graalvm-demos
cd graalvm-demos/scala-examples/scalac-native
-
Then enter the
scalac-substitutions
subfolder and build the project withsbt
:cd scalac-substitutions
sbt package
cd ..
-
Build the native image of the Scala compiler:
./scalac-image.sh
The produced native image is called
scalac
and has no dependencies on the JDK.The script
scalac-native
calls the generated compiler and passes all the required parameters (just likescala
does).
Compare to the JVM on the first run:
time $SCALA_HOME/bin/scalac HelloWorld.scala
real 0m2.315s
user 0m5.868s
sys 0m0.248s
time ./scalac-native HelloWorld.scala
real 0m0.177s
user 0m0.129s
sys 0m0.034s
When compiled with Profile-Guided Optimization (PGO) the native scalac
is as fast as the one running on the JVM (with the C2 compiler).
For macros to work, the macro classes must be known to the image builder of the Scala compiler.
-
First, try a
scalac
image that includes macro, run:./scalac-native macros/GreetingMacros.scala -d macros/ ./scalac-image-macros.sh
-
Now you can compile a project that uses macros from
GreetingMacros.scala
:./scalac-native -cp macros/ HelloMacros.scala
-
Run the compiled program with:
scala HelloMacros
Hello, World!