openrewrite / rewrite-templating

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

Mismatch in parameters of before/after not recognized #107

Open Bananeweizen opened 3 months ago

Bananeweizen commented 3 months ago

What is the smallest, simplest way to reproduce the problem?

Due to copy/pasting an existing recipe first I accidentally created an after method with more arguments than the before method:

    static final class Reproducer {
        @BeforeTemplate
        BufferedReader before(Path path, Charset charset) throws IOException {
            return new BufferedReader(
                    new InputStreamReader(new BufferedInputStream(Files.newInputStream(path)), charset));
        }

        @AfterTemplate
        BufferedReader after(Path path, String content, Charset charset) throws IOException {
            // the second argument "content" does not exist in the before template
            return Files.newBufferedReader(path, charset);
        }
    }

What did you expect to see?

It would be good to raise an explicit error that the @AfterTemplate method doesn't have the same number (and types and order...) of arguments like the @BeforeTemplate method.

What is the full stack trace of any errors you encountered?

The generated code doesn't compile, therefore the error doesn't go unnoticed. But users might still be confused about the exact reason.

FilesRulesRecipes.java:[480,131] incompatible types: <nulltype> cannot be converted to int

grafik

Are you interested in contributing a fix to OpenRewrite?

Yes.

Side note: The above recipe (and multiple variants of it for other nestings of readers/streams) would be a valid recipe for rewrite-java probably. I just stumbled over this in real code yesterday.

timtebeek commented 3 months ago

Agree with both points above: Best to explicitly warn when after requires more parameters than any of the before templates.

And yes would make a neat addition to have that simplification as an official recipe; I'm thinking rewrite-migrate-java would fit best, as some of those methods are only available in Java 8+.