Feature request: Compile time code generator annation

I think we need a compile time code generator annotation.
Something like that:

@CompileTimeGenerator
fun compileRegex(str:String):Regex{
    val a=template.newClassExtends(Regex::class) // return a blank Class<> extends Regex.
    a... // write logic here. such as Logic or source code.
    return a // compiler auto generate code to instantiation this Class<>.
}

fun foo(input: String){
    compileRegex("[A-z]+").match(input)...
}

The regex compile can done during code compile.
I think there are more advance action can do by this feature.
Before that, we need a pure function analysis?

I don’t understand what the compiler is supposed to do. What exactly is supposed to happen here?
What is this template variable and what is supposed to happen.
Do you want to create the instance of Regex at compile time? In that case it’s not possible, best case you can create it at the startup time of the porgram, which you can already do with global variables

val specialRegex = Regex("[A-z]+").apply {
   /* your logic here */ 
}

Other compile time code generation can already be done with annotation processing on the JVM and if you want compiler plugins (any target), but they don’t have a stable api yet.

Sorry, I means we can add this feature to compiler, it helps user running code in compile time.

What you probably want is an analog of constexpr from C++. I am not sure it is really a good idea. Even in C++ it produces a lot of problems with deciding what is compiled when and if the constexp could depend on non compile-time constants. In Kotlin the use-cases of constexpr are mostly solved by inline functions. In JVM you do not need to bother with those because those expressions are compiled and memoized by JIT. No need to move them to compile time. The same is probably goes for JS. Native lacks JIT, so maybe there is some reasoning behind it, but still introducing those could create more problems, then it solves. There should be some very compelling reasons for introducing it.

1 Like

Thank you.

Might be worth following this.