openrewrite / rewrite-templating

Automated templating using code snippets.
Apache License 2.0
16 stars 7 forks source link

Exceptions thrown from before templates should not be added to Preconditions #30

Closed timtebeek closed 10 months ago

timtebeek commented 1 year ago

What problem are you trying to solve?

When a before template throws a specific exception, that now makes it's way into the preconditions, as seen in https://github.com/openrewrite/rewrite-migrate-java/commit/4bfadd20f38ec86ccbe80aaa77789c23d3ec3cd7. That means the templates will fail to match, since the exception is unlikely to be used in the matched template.

Describe the solution you'd like

Do not add exceptions to preconditions.

Have you considered any alternatives or workarounds?

Additional context

timtebeek commented 10 months ago

Had some discussions with @knutwannheden around this; excluding the declared thrown exceptions from the lambda seems right, although we might want to double check if that is even an issue still.

We should be able to collect the imports using something like this:

 Set<Symbol> allImports = new HashSet<>(ImportDetector.imports(template.getBody()));
 allImports.addAll(ImportDetector.imports(template.getReturnType()));
 template.getParameters().forEach(p -> allImports.addAll(ImportDetector.imports(p)));
 template.getTypeParameters().forEach(p -> allImports.addAll(ImportDetector.imports(p)));
knutwannheden commented 10 months ago

Excluding the method's throws clause is important as it will otherwise add wrong UsesType preconditions. One example would be when the template's throws clause lists runtime exceptions. The code being matched might not have any corresponding catch or throws, so there should not be any corresponding UsesType.