diff --git a/rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateMatchTest.java b/rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateMatchTest.java index 35dff7db112..d3e8c82a19e 100644 --- a/rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateMatchTest.java +++ b/rewrite-java-test/src/test/java/org/openrewrite/java/JavaTemplateMatchTest.java @@ -85,6 +85,35 @@ class Test { )); } + @Test + void matchNamedParameterMultipleReferences() { + rewriteRun( + spec -> spec.recipe(toRecipe(() -> new JavaVisitor<>() { + @Override + public J visitBinary(J.Binary binary, ExecutionContext ctx) { + return JavaTemplate.matches("#{i:any(int)} == 1 && #{i} == #{j:any(int)}", getCursor()) + ? SearchResult.found(binary) + : super.visitBinary(binary, ctx); + } + })), + java( + """ + class Test { + boolean foo(int i, int j) { + return i == 1 && i == j; + } + } + """, + """ + class Test { + boolean foo(int i, int j) { + return /*~~>*/i == 1 && i == j; + } + } + """ + )); + } + @SuppressWarnings({"ConstantValue", "ConstantConditions"}) @Test void extractParameterUsingMatcher() { diff --git a/rewrite-java/src/main/java/org/openrewrite/java/internal/template/Substitutions.java b/rewrite-java/src/main/java/org/openrewrite/java/internal/template/Substitutions.java index 5ab5d1b2822..0db385f9eb5 100644 --- a/rewrite-java/src/main/java/org/openrewrite/java/internal/template/Substitutions.java +++ b/rewrite-java/src/main/java/org/openrewrite/java/internal/template/Substitutions.java @@ -50,8 +50,6 @@ public String substitute() { Map typedPatternByName = new HashMap<>(); String previous = substituted; substituted = propertyPlaceholderHelper.replacePlaceholders(substituted, key -> { - int i = index.getAndIncrement(); - String s; if (!key.isEmpty()) { TemplateParameterParser parser = new TemplateParameterParser(new CommonTokenStream(new TemplateParameterLexer( @@ -69,13 +67,16 @@ public String substitute() { throw new IllegalArgumentException("The parameter " + paramName + " must be defined before it is referenced."); } } else { + int i = index.getAndIncrement(); s = substituteTypedPattern(key, i, typedPattern); if (ctx.typedPattern().parameterName() != null) { - typedPatternByName.put(ctx.typedPattern().parameterName().Identifier().getText(), s); + String paramName = ctx.typedPattern().parameterName().Identifier().getText(); + typedPatternByName.put(paramName, s); } requiredParameters.incrementAndGet(); } } else { + int i = index.getAndIncrement(); s = substituteUntyped(parameters[i], i); requiredParameters.incrementAndGet(); }