soc
soc

Reputation: 28413

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?

Upvotes: 6

Views: 322

Answers (3)

Silas
Silas

Reputation: 1150

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

Upvotes: 2

0__
0__

Reputation: 67280

Also see The Scala Compiler Corner. And another related Stackoverflow question, and another one (referring you to treeFrom from the scala-refactoring project).

Upvotes: 1

Philippe
Philippe

Reputation: 9742

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.

Upvotes: 1

Related Questions