Samuel Neff
Samuel Neff

Reputation: 74949

Modify Kotlin compiled code output based on annotation (not generate separate code)

Is there a way to create a Kotlin compiler plugin that can modify the code being written?

I don't want to create separate generated code but actually modify the code itself.

For example, given this source:

Original

@Composable
fun MyScreen() {
    Surface {
        Button(onClick = { 
            println("Clicked") 
        })
    }
}

I want to change the output code to be this:

Modified by plugin

@Composable
fun MyScreen() {
    Surface {
        Button(onClick = 
            track("MyScreen", "Surface", "Button") {
                println("Clicked")
            }
        )
    }
}

Or even just change the import:

Original

import androidx.compose.material.Button

@Composable
fun MyScreen() {
    ...
}

Modified by plugin

import com.mycompany.project.wrappers.Button

@Composable
fun MyScreen() {
    ...
}

Upvotes: 1

Views: 376

Answers (1)

Nikola Despotoski
Nikola Despotoski

Reputation: 50578

KSP doesn't offer modifying function bodies, because KSP is unable to look at function body.

You can achieve modification of function body expression if you use write your own Kotlin compiler plugin. Kotlin compiler plugin will allow you to modify the code in compile-time.

Upvotes: 1

Related Questions