Can a compiler plugin add new syntax to Kotlin?

I was working on a plugin that makes Kotlin support implicit boolean conversions.

The plugin was expected to let code like

var a: Int? = null
if (a) {
    println("a is not null")
} else {
    println("a is null")
}

could be compiled successfully, and transformed into code like

var a: Int? = null
if (a != null) {
    println("a is not null")
} else {
    println("a is null")
}

I was thinking about transfroming Kotlin IR to achieve the goal, but the compiler won’t let the code generate IR.

Searched kotlin-compiler source code, I found out that I should block the original WhenConditionChecker to let the code generate wanted IR. But I could not find the way to do that.

Then I search some information about kotlin-complier-plugin, almost all of them are talking about annotations.

I was a little confused, could my plugin REALLY be written out?

I’m definitely not an expert in this field, but it sounds like you need to write a plugin for the compiler frontend. I believe existing compiler plugins are all backend (?). So you probably should start by searching if currently it is at all possible to write plugins for the frontend.

It is also possible I’m entirely wrong :stuck_out_tongue_winking_eye:

Bear in mind that what you create wouldn’t (quite) be Kotlin any more…

I know that, so I have an alternative solution of _if_.kt.

But in the mean time, I still curious about this question.

Why are you trying to do that? Kotlin strives to make everything explicit, and adding obscure, hardly–predictable semantics to the language just to avoid typing != null or .isNaN().

For what it’s worth, your intention is not about syntax, but rather about the type system, since you want implicit casting — so it regards semantics.

While I’m not experienced with writing Kotlin compiler plugins, I believe their reasoning is not to change Kotlin semantics.
As far as I know about Kotlin IR transformers m, they’re meant to transform the semantics of what the generator will be given to emit the output for the targeted platforms — not to affect the semantics of the language. They’re kind of “transparent” for users; consider AtomicFU and Jetpack Compose — none of these affects the semantics of the users’ Kotlin code.

1 Like