What's the best way to achieve this? ```// Transfo...
# compiler
l
What's the best way to achieve this?
Copy code
// Transform all instances of this call...
foo()

// ...into this via a compiler plugin:
foo("Hello")
I'm playing around with
CallResolutionInterceptorExtension
but wondering if there are any other extensions I should be looking at.
j
If you are sure method with the same name and string parameter exists, you can use ExpressionCodegenExtension - but it's JVM only
You could also use IR manipulation, but I haven't done that - I know arrow Meta is using that.
l
Awesome thanks! I'll dig into that. If you happen to know of a good example using ExpressionCodegenExtension to alter a function call let me know!
I'm sure there's a number of things I'm doing wrong here but would appreciate any pointers:
Copy code
class FooExpressionCodegenExtension(private val project: Project) : ExpressionCodegenExtension {

    override fun applyFunction(
        receiver: StackValue,
        resolvedCall: ResolvedCall<*>,
        c: ExpressionCodegenExtension.Context
    ): StackValue? {
        val newExpression = KtPsiFactory(project).createExpression("foo()")
        return c.codegen.gen(newExpression)
    }
}
With the code above I'm getting the following error:
Copy code
No resolved call for 'foo()' at (2,1) in dummy.kt
I've taken a look at some different API's and it seems like I'm always getting stuck figuring out how to provide a
ResolvedCall
. Are there any examples I can take a look at to figure this out or is there any tribal knowledge that anyone can provide here?
Same result with
Copy code
return StackValue.expression(
            Type.getMethodType("()V"),
            KtPsiFactory(project).createExpression("foo()"),
            c.codegen
        )
Also, what are you trying to achieve? Codegen is usually used for generating custom declarations, not rewriting existing ones.
Here you go: https://github.com/jereksel/leland-compiler-plugin-example - there are some unchecked casts and unsafe null dropping, but it works fine.
l
Thank you this is super helpful! I'm trying to implement a prototype of a something similar to Swifts
#line
/
#file
/
#function
/ etc macros:
Copy code
// Swift 
func logFunctionName(string: String = #function) {
    print(string)
}
func myFunction() {
    logFunctionName() // Prints "myFunction()".
}
I feel like it would have been really difficult to figure out on my own what you've implemented in that example. Are there any resources available to learn more about these APIs?