Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 822
soc Avatar asked Dec 09 '11 01:12

soc


People also ask

Can a compiler be used to compile its own source code?

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.

How does the Scala compiler work?

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.

Which command is used to compile and run Scala program?

To compile the code, type "scalac hello_world. scala" and press enter.

Which compiler is used in Scala?

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.


2 Answers

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

like image 145
Silas Avatar answered Oct 27 '22 00:10

Silas


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.

like image 26
Philippe Avatar answered Oct 27 '22 00:10

Philippe