I'm writing a new compiler that supports kotlin sy...
# compiler
s
I'm writing a new compiler that supports kotlin syntax, how do I reuse existing frontend code? like parsing, ir
h
What exactly do you want to do? The Kotlin compiler heavily uses IntelliJs code base, do you really want to reuse that? Or does your compiler also uses IntelliJ? If so, to get the PSI tree, there is a KotlinCoreEnvironment that setups the IntelliJ environment including the lexer, parser etc. Then you create/add your Kotlin (virtual) files to the index and you get a KtFile, a Kotlin PSI file with the syntax tree. I did this here, to run the Java2Kotlin converter: https://github.com/hfhbd/j2k/blob/main/j2k-core/src/main/kotlin/J2KConverter.kt Or do you want to get only IR code as file? I think, there is a compiler option that dumps the IR, so you could run the compiler in a separate process.
s
I'm trying to write a new compiler that compiles (a subset)kotlin code to native target use LLVM, without gc etc, it's like zig in kotlin syntax. Rewrite entire frontend takes time. It also have a different stdlib because of no GC. I can use tree sitter as lexer, but I want to reuse all the code possible. So I can directly start write kotlin ir to LLVM, without spend time on existing things.
d
The Kotlin compiler heavily uses IntelliJs code base
Not entirely true. There are quite few things from intellij which are actually used by the compiler: • parser abstraction (
LighterASTNode
) • PSI interfaces for implementation of `KtElement`s (mostly used by the IDE plugin, the compiler works without PSI) • java analysis for java source files (the biggest part, which we want to implement by ourselves) • some infrastructure like filesystem IO for searching in classpath
🙏 2
As for original question: almost the whole compiler is packed into
org.jetbrains.kotlin:kotlin-compiler
and
org.jetbrains.kotlin:kotlin-compiler-embeddable
jars, so you can depend on one of them and reuse everything from the compiler programmatically AFAIR those jars don't include only Native backend, which is included into
org.jetbrains.kotlin:kotlin-native-compiler-embeddable
(some classes probably duplicated between
compiler
and
native-compiler
) The difference between
...compiler
and
...compiler-embeddable
is that the
embeddable
jar contains shaded dependencies: almost all classes not from
org.jetbrains.kotlin
package are repackaged (so
a.b.Some
class becomes
org.jetbrains.kotlin.a.b.Some
). This is needed to avoid potential problems with dependencies versions in projects which depend both on kotlin compiler and some of its (separately, probably transitive)