Writing a lambda-inspecting compiler extension

I would like to write a compiler extension and/or annotation processor that does the following:

  1. is triggered by the presence of a specific annotation on a lambda:

    @Target(AnnotationTarget.FUNCTION)
    annotation class MyAnnotation
    
    val someLambda = @MyAnnotation { n: Int -> n + 1 }
    
  2. can inspect (read-only) the Kotlin AST of the lambda;

  3. can fail the compilation with an error, for example if the code inside the lambda contains a Kotlin feature that is not supported by my library;

  4. generates data (not code!) that will be used by a runtime library, either by creating new source files or (better) by storing the data as further annotations to the lambda being compiled.

I’m looking at the interfaces in org.jetbrains.kotlin.extensions, but they are somewhat complicated and undocumented.

Can anybody recommend the simplest way to achieve the points above?

Interesting indeed. I have my own use case for such a compiler extension (unfortunately compiler plugins are not quite stable yet). What I want is the ability to declare on a function parameter that the function cannot capture the this pointer (or other local variables) implicitly.

Does anybody have any idea how to implement something like this? Can a standard (kapt) annotation processor inspect the original Kotlin AST?

No. You need a compiler plugin for that.

1 Like