2018-03-18

Programmatically compile Kotlin code

Compile Kotlin in Kotlin, dawg!

Here's a small braindump again, because I don't want to forget how I managed to compile Kotlin files programmatically. There are some very small discussions online, for example this one, but I find existing usages too complex and there are too many things that didn't work for me at the first few tries.

So there's a very convenient artifact that seem to contain everything one needs in order to call a Kotlin compiler from within code and that's published for every Kotlin release. Use it with


    compile group: 'org.jetbrains.kotlin', name: 'kotlin-compiler-embeddable', version: "$kotlin_version"

The following snippet instantiates a compiler, passes a file and some other properties to it and executes compilation. The resulting class file can be found in the given output directory.


val output = File("/home/myuser/out")

K2JVMCompiler().run {
    val args = K2JVMCompilerArguments().apply {
        freeArgs = listOf(File("/home/myuser/KotlinFile.kt").absolutePath)
        loadBuiltInsFromDependencies = true
        destination = output.absolutePath
        classpath = System.getProperty("java.class.path")
                .split(System.getProperty("path.separator"))
                .filter {
                    File(it).exists() && File(it).canRead()
                }.joinToString(":")
        noStdlib = true
        noReflect = true
        skipRuntimeVersionCheck = true
        reportPerf = true
    }
//        output.deleteOnExit()
    execImpl(
            PrintingMessageCollector(
                    System.out,
                    MessageRenderer.WITHOUT_PATHS, true),
            Services.EMPTY,
            args)
}

The usage depends on the project where it is used, for example it coult be necessary to add a different classpath or add the classpath and a stdlib or something else.

EDIT: I'm sure I found this snippet, or a similar one in the internet, but I can't find it anymore. If you found it, let me know and I will link it as source.