openrewrite / rewrite

Automated mass refactoring of source code.
https://docs.openrewrite.org
Apache License 2.0
2.22k stars 330 forks source link

Parse and expose nullability of types for use in recipes #3221

Open timtebeek opened 1 year ago

timtebeek commented 1 year ago

Kotlin quite clearly has explicit nullability, but some Java projects can somewhat express the same with nullability annotations. In addition to that we can deduce nullabillity once for instance a method has been called on an object.

It would be great if we could capture and expose this information through our type system, such that recipes can query this when inserting code snippets. Notably this came up recently in https://github.com/apache/maven-pmd-plugin/pull/124#issuecomment-1515133417, where we want to forgo adding null checks where they are not needed. Ideally this is something we determine ahead of time, even if limited.

Once exposed we can also write clean up recipes that remove excessive null checks. Even if we start small (for instance only looking at Kotlin types, or some nullability annotations, then we can gradually expand this over time, to bring more value to repeatedly running recipes that use this information.

I've not looked at implementation specifics yet, merely discussed this with Knut as it came up recently for Kotlin on Slack.

knutwannheden commented 1 year ago

In addition to the nullability information which can be determined from the declarations (Java nullability annotations or Kotlin / TypeScript types) and be amended to the JavaType objects, there is also the aspect of the data flow analysis (e.g. do we know that this variable is null or not null at this point). The latter would have to be computed from the LST using a visitor. Both these sources of information are useful on their own (and can also be developed independently to some extent), but for the full benefit, it would be great if recipes could rely on the combined result of both these components when making a decision on how to generate a certain piece of code.

blipper commented 1 month ago

Note that native null restricted and null-types is coming to the language soon. https://openjdk.org/jeps/8303099. After drops https://openjdk.org/jeps/492 so JDK 24/25/26? Probably worth getting started on this sooner rather than later imo.