Kotlin AST Transformation for embedded scripting


We are working on a product which should allow end customers write business logic in some language. We are exploring Kotlin as that language.

One of the most important aspect in that case is security of the code our customers would write. We need to be able to understand Kotlin code they have written, rewrite some of that code and compile to java class.

How do we go about compiling the code they write at our product runtime, rewriting their code to inject logging, and limits or other monitoring to ensure the stability?

Any help or direction is appreciated.


For reading Kotlin and transforming it you could go the way of borrowing the parser implementation. Alternatively bytecode editing is the more popular way to handle things like injecting logging etc.

As far as security is concerned, use classloaders and java’s security management system (you could audit api’s used if really needed - but that quickly becomes difficult or restrictive). You may look at a compiler extension if you want to compile as well (or you generate adjusted kotlin source).


Thank you @pdvrieze. Can you please share some links to documents or tools that makes use of it, if you are aware?

Groovy has first class support for these type of transformations via AstTransformations. I was hoping Kotlin has something like that.


As I understand it, Kotlin compiler extensions/plugins are still very much a work in progress and are certainly (very) poorly documented. For bytecode instrumentation, there are many java based examples, and you probably want to have a look at the asm library.


thank you @pdvrieze


This just appeared on Reddit: https://blog.frankel.ch/sonarqube-plugin-kotlin/1/#gsc.tab=0 - and references an ANTLR grammar for Kotlin that I didn’t know about until now - https://github.com/antlr/grammars-v4/tree/master/kotlin - may be useful for what you’re doing.