How can I create my own compiler backend?

Hey there!
I’ve only used Kotlin for 2 weeks and I have no former experience with Java/JVM, when I’m trying to do research on this topic on my own, I stumble upon many keywords I’m not familiar with. I hope you’ll be able to help :).
So I would like to create my own Kotlin backend, which would output a new, not supported by default language - my choice is Lua. While I know something about compiler design, I completely don’t know where to start in Kotlin.
From what I understand, the best way to start would be to create a gradle plugin, so I could tell it to compile into Lua like that:

kotlin {
    lua {
        // etc...
    }
}

I have completely no idea how to make it run my custom compiler (assuming I already have one) from build.gradle.kts.

Now as to the compiler itself… Kotlin compiler is pretty complicated. Maybe instead of making my own compiler from scratch, I could use existing JS IR compiler.
What steps need to be done, to move the entire IR JS compiler into a custom gradle plugin?
Also, instead of duplicating js frontend and js backend, maybe I could run the compiler with just the last codegen step replaced? The classes which translate JS AST to actual javascript file.
But I have no idea where to even start :slight_smile:. How to programatically run the compiler pipeline for a given directory, then wait until the last (JS) compiling step and use my class instead of it?
Is there documentation for kotlin-compiler-embedded or any guides? Both on making gradle and compiler plugins.

Any help would be appreciated D:

2 Likes

A Lua backend would be pretty neat. Making a backend is definitely a challenge but there is at least one example of a community-made backend, this one is for Python: [Idea] Python backend. See that discussion for links to the Slack channels and repos.

I’m not sure if it uses the new IR or not. It’s passed a lot of the backend unit tests and has been under active development until this last June when they paused development until they get more resources (see the Slack channels).

Good luck!

3 Likes