Can I run the compiler directly from Kotlin in the...
# compiler
m
Can I run the compiler directly from Kotlin in the same JVM?
k
I think the embeddable compiler artifact is what you want?
m
Ah, the embedded compiler, didn't think of that one! I'll check it out tomorrow and see if I can get it running in-process including annotation processing 👍 Thanks 🙏
t
If you want to compile Kotlin code and run annotation processors you can use my AP library. It includes a compile-testing module with a pre-release on jitpack
m
Thank, I'll check it out 🙂
Doesn't that one spawn another process, so it's not in-process?
t
I think the kotlin compiler is in process and the java one isn't (usually). But what do you care what process it runs in?
m
I want to pass an instance of my AP directly to the compiler
and then just get list of messages & exit code
just like in compile-testing
and I'm almost there I think 🙂
I got it ❤️
Copy code
val result = KotlinCompiler()
	.jvmTarget(KotlinJvmTarget.v1_8)
	.processors(AnnotationProcessor())
	.sourceFiles(File("tests/samples/Sample1.kt"), File("tests/samples/Test.java"))
	.withSystemClasspaths()
	.compile()

println(result.messages.joinToString("\n"))
println(result.generatedFiles.joinToString("\n") { "Generated: ${it.path}" })
println(result.exitCode)
Copy code
logging: Using Kotlin home directory <no_path>
logging: Configuring the compilation environment
warning: Unable to find kotlin-stdlib.jar in the Kotlin home directory. Pass either '-no-stdlib' to prevent adding it to the classpath, or the correct '-kotlin-home'
warning: Unable to find kotlin-script-runtime.jar in the Kotlin home directory. Pass either '-no-stdlib' to prevent adding it to the classpath, or the correct '-kotlin-home'
warning: Unable to find kotlin-reflect.jar in the Kotlin home directory. Pass either '-no-reflect' or '-no-stdlib' to prevent adding it to the classpath, or the correct '-kotlin-home'
Generated: hey/Sample1JSONCodec.kt
OK
👏 1
t
How do you compile java files? I don't see any call to javac
m
Kotlin compiler does that heavy lifting
t
Are you sure? I don't think so
try calling your K2JvmCompiler with only java files. It won't even work
m
I've used it with a Java file too and it worked just fine. Alos saw some core in the compiler which runs javac
I didn't try only Java, there was at least one KT. Maybe that's a different code path 😮
t
as far as I know javac is only called to run apt, not to compile Java files. That has to be done by the build system
and if only java files are given, K2JvmCompiler won't run at all
m
hmm let me double check
You're right, that doesn't work. Let's see what can be done here 🤔
t
Let me just say the whole thing isn't as straight-forward as you think
m
I still think it is
So compiling java works just fine. But I need to find a way around the limitation that there must be at least one KT file