How to interact with the compiler in the Scala code itself?

I wonder how many ways there are to interact with the Scala compiler outside of normal, "call it on the command line to compile my sources.

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

+6
source share
3 answers

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

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

Update: this should answer AST question (may be deprecated since 2009): Scala AST in Scala

+2
source

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-scary Global class.

Overriding the computeInternalPhases method, you can use only some compiler steps (for example, before refchecks , use it only as an analyzer / typechecker), and you can add your own phases (plugins) as you expect. Of course, you can also fully generate class files.

So yes, it is definitely possible. In the end, the compiler itself also runs on the JVM.

+1
source

Also see Scala Compiler Angle . And fooobar.com/questions/423827 / ... and the other (referring to treeFrom from the scala -refactoring project ).

+1
source

Source: https://habr.com/ru/post/903425/


All Articles