Kotlin AST


#1

So I may be a unicorn, but I love code generation.  I have a project critter that I use to generate some code for use with Morphia. Currently, i'm using a project called roaster to parse my Morphia entities and then generate some code around that.  I'm in the process of migrating a project that uses critter to Kotlin and am presented with a problem.  With no more Java code to parse, i have to either stop using this generated code or maintain it by hand.  I *could* do weird things with maven lifecycles and plugins and leave small segments of code in Java and, thus, parseable.  That's entirely doable but decidedly ugh.

Now what I’d love is to update critter to be able to do the same for Kotlin files but that’s where I hit the roadblock.  Is there some API I could use or is my only option at this point to shoehorn the kotlin-compiler API in to something that sort of fits the bill?  This is not a great option for obvious reasons but not necessarily out of the realm of possibility.  Roaster leverages Eclipse’s AST libs for doing its magic.  How accessible are the Kotlin bits like this?


#2

There is no API for building Kotlin ASTs outside of kotlin-compiler, and so far we have no plans to provide one. Using the Kotlin compiler to build ASTs isn't too hard - you need to create an instance of KotlinCoreEnvironment by calling its method createForProduction(), and then use PsiFileFactory.getInstance(environment.project).createFileFromText() to parse a given code fragment.


#3

Thanks. I'll give that a whirl.


#4

See also http://stackoverflow.com/questions/32664842/how-to-get-kotlin-ast


#5

There is actually quite a few code quality and build process plugins (to Maven / Gradle) which are quite dependent on a stable and decently simple-to-use AST (including JavaDoc/Dokka scope) for Kotlin. Hence it would simplify adoption quite a lot if you would expose it for us.

Just to take 2 examples:

  1. The PMD and Checktyle plugins use ASTs to scan the source code for syntax anomalies/problems.
  2. The JAXB2-maven-plugin uses Doxia (which is JavaDoc-specific, so we need an equivalent for Dokka/KDoc) to extract JavaDoc comments and inject those into XSDs generated from annotated classes.

These - and other kinds of supporting and quality-enhancing technologies need to parse Kotlin sources to improve enterprise-wide overall quality of code. Please help us do that in Kotlin as well - it is simply required to increase adoption.