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: A SonarQube plugin for Kotlin - Paving the way - and references an ANTLR grammar for Kotlin that I didn’t know about until now - grammars-v4/kotlin at master · antlr/grammars-v4 · GitHub - may be useful for what you’re doing.