openrewrite / rewrite-kotlin

Work-in-progress implementation of Kotlin language support for OpenRewrite.
Apache License 2.0
43 stars 12 forks source link

Support Kotlin-based templates #218

Open knutwannheden opened 1 year ago

knutwannheden commented 1 year ago

What problem are you trying to solve?

When modifying Java code the safest and often easiest way is to use JavaTemplate. For Kotlin this is currently not possible, because JavaTemplate uses a JavaParser (and not a KotlinParser) and there is no corresponding mechanism in rewrite-kotlin.

Describe the solution you'd like

Modify JavaTemplate (in rewrite-java) so that it can be provided with a KotlinParser rather than a JavaParser and then use this mechanism to parse context-free templates.

Supporting context-sensitive templates will be more work and will probably require a new KotlinTemplate type.

Have you considered any alternatives or workarounds?

Additional context

Are you interested in contributing this feature to OpenRewrite?

nmck257 commented 9 months ago

Hey @knutwannheden, Naïve question: is there a possible implementation where a J tree (like from a JavaTemplate) is converted into a K tree?

This feels syntactically possible, would provide some level of compatibility for existing recipes written using JavaTemplate, and would also open up for features where OpenRewrite is used to translate code between languages.

knutwannheden commented 9 months ago

This is indeed an interesting topic. While the Kotlin printer should be able to print a J tree (since K is an extension of J), the code would in many cases not be idiomatic Kotlin code and I am afraid it would in many cases not even be correct code. This then indeed requires some type of transformation.

We do have a concept for how a JavaVisitor can be adapted so that it can be adapted by a KotlinVisitor to also be able to process Kotlin LSTs, but we are still investigating how to best use this to make Java recipes applicable to Kotlin code. Further, this would not really help when a recipe uses JavaTemplate to emit new code.

We haven't yet worked out how exactly these things should all fit together, but we would definitely want as many Java recipes as possible to be compatible with Kotlin. Independent of this I think it makes sense to have a KotlinTemplate which allows Kotlin developers to more easily author Kotlin recipes.

nmck257 commented 9 months ago

Agreed, KotlinTemplate is valuable independent of any enhancements to make java recipes more effective on kotlin code.

And I think that starts to answer some of the questions I raised over here: https://github.com/openrewrite/rewrite-migrate-java/issues/367

I suppose it wouldn't take much code to play with using the kotlin printer on a J tree on my machine; I'd be curious to see just how far it can be from valid (even ignoring idiomatic)