Skip to content

Commit

Permalink
Fix bug in Substitutions related to named parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
knutwannheden committed Oct 1, 2023
1 parent 4a6a157 commit 5e4742d
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,6 @@ public String substitute() {
Map<String, String> 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(
Expand All @@ -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();
}
Expand Down

0 comments on commit 5e4742d

Please sign in to comment.