Hey, I am new to Scala and I would like to instrument the code of an existing Scala project.
Basically, I will fork a Scala project and then I want to write a transformer program which parses the project’s source code and adds certain statements at certain lines of code.
Hence, I need a Scala code parser and transformer framework.
Is there any Scala parser/transformer project which helps me to do this?
I have found https://docs.scala-lang.org/overviews/reflection/symbols-trees-types.html#creating-trees but it seems more like runtime reflection?
Have a look at https://scalameta.org/
On a second thought, depending on your use case, instrumentation on the bytecode level might be more suitable: http://byteman.jboss.org/
Really depends on your requirements. If you want to modify the source code, then I’d probably recommend Scalafix.
thx for the answers. I think that bytecode level will be too low level since I want to identify certain things like pattern matching etc.
I will give scalameta a try.
I have tested scalameta and it works nice for modifying the AST.
However, I came to the conclusion that I probably need type information as well. I have asked on StackOverflow: https://stackoverflow.com/questions/57132249/how-to-get-the-type-of-a-variable-with-scalameta-if-the-decltpe-is-empty
It seems that I have to compile the project first, generating a semanticdb with the type information and then I can instrument the source code but I have to use the generated semanticdb files to get the type information of the expressions.
This seems rather complicated.
Is there some easier way to get the type information while modifying the AST?
For example, would it be easier to write a compiler plugin for Scala which probably has all the information?
So far I have only found this: https://docs.scala-lang.org/overviews/plugins/index.html
It seems like the user would have to add only:
addCompilerPlugin("bla" % "myplugin" % "1.0")
and the plugin could instrument the source code during the compilation phase and would have all the type information?
However, it seems to use internal AST types of Scala instead of scalameta.
Does anyone have experience with writing compiler plugins or can recommend an easier way than generating the scalametadb files and using them while transforming the AST?
sounds like a job for a compiler plugin