kotlinx / ast

Generic AST parsing library for kotlin multiplatform
Apache License 2.0
313 stars 22 forks source link

Source code generation from the AST #43

Open vinaysshenoy opened 3 years ago

vinaysshenoy commented 3 years ago

I've been working on a meta-programming tool that can process generated code for the Android Room database and transform it to insert profiling statements. Since this generates Java code, I've used JavaParser to read the Java code into an AST, transform it and output the transformed AST as source code (since this is a feature that JavaParser supports) to be used in the final build.

I also want to add support for SQLDelight. However, that generates Kotlin code, so I need a tool that can not only parse the generated Kotlin code, but lets me modify it and output transformed source code.

As far as I can tell, kotlinx.ast only supports reading the source code and not generating code from the AST. Would I be correct in that?

drieks commented 3 years ago

Hi @vinaysshenoy, yes, this library only supports parsing of kotlin code. Sadly, I have no time to implement transformation or writing logic. In my private project, a small meta programming tool, I'm using kotlinx.ast to parse the kotlin source and https://github.com/square/kotlinpoet to write the generated code. The first step is transforming the string represeting the full kotlin file into an abstract syntax tree (ast), the next step is reducing this ast into easier to handle representation (for example KlassDeclaration), both steps are implemented here in kotlinx.ast. Then I'm parsing the Klass-classes to create domain specific data classes, in my case for example I'm looking for beans and bean factories, classes and fun/val with some sort of annotations. The last step is converting the domain specific data classes to kotlin code using kotlinpoet.

If you need to transform kotlin code you can also try to use https://meta.arrow-kt.io/ (a framework for writing kotlin compiler plugins), https://resources.jetbrains.com/storage/products/kotlinconf2018/slides/5_Writing%20Your%20First%20Kotlin%20Compiler%20Plugin.pdf (how to write compiler plugins directly) or https://github.com/google/ksp (Kotlin Symbol Processing)

vinaysshenoy commented 3 years ago

Alright, thanks for the information! I'll take a look at what you've suggested.