Hi, I'm trying to add a new operator to the kotlin...
# compiler
a
Hi, I'm trying to add a new operator to the kotlin compiler source code for academic purposes, a '**' that should be translated to '.pow' (so "2.0 ** 5.0" should be the same as "2.0.pow(5.0)"). By replicating the '*' (times) operator I'm able to add it to the lexer, and it is correctly identified and replaced, even in the kotlin bytecode viewer. Unfortunately when compiling it says "Error:(9, 17) Kotlin: 'operator' modifier is required on 'pow' in 'kotlin.math'". The issue is: the pow operation doesn't have the keyword operator, but I can't add it because otherwise I'm not able to compile it. The same also happens if I try to add a new function (let's say "public operator fun powOper(other: Int): Int" because there is no powOper in the Kotlin version I'm using to compile the source code, so I can't add the operator keyword there. What can I do?
y
You can try having some form of "prelude" library that just has
public operator fun Double.powOper(other: Int): Int = pow(other)
, or you can even define it yourself in the source code that you're compiling.
a
I can't define it in the source code itself because otherwise I can't compile it (because I need kotlin to compile kotlin...). I guess using a separated library is the way to go, but I'm not sure yet how to.
y
I'm not talking about defining it in the modified kotlin compiler's source code, but instead define it in the code that is meant to be compiled by the modified kotlin compiler
as in let's say you have a main.kt that uses this new pow operator:
Copy code
fun main(){
    println(5.0 ** 2) // should print 25
}
// Add the powOper definition here then to make it work
operator fun Double.powOper(other: Int): Double = this.pow(other)
👍 1
s
I think this mismatch can be solved if you create the compiler artifact which allows this new function and then use it to compile stdlib with your new changes
I think you can publish it to maven local and then override it to use local version somewhere in gradle properties (I think by version)
a
@Youssef Shoaib [MOD] your suggestion works! Thank you very much, I didn't though of that. @shikasd Now that I'm able to test with Youssef's trick I'll try your suggestion too.
y
@Abel happens to the best of us lol! It's probably because like when you go deep into a specific complex topic like compilers you stop considering simple solutions because they're too simple!
😅 1