Skip to content

Commit

Permalink
Named JavaTemplate parameters
Browse files Browse the repository at this point in the history
  • Loading branch information
jkschneider committed Sep 30, 2023
1 parent 6873fbd commit ba69707
Show file tree
Hide file tree
Showing 36 changed files with 807 additions and 706 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,6 @@ public static int indexOf(String text, Predicate<Character> test) {
* @return the number of times the substring is found in the target. 0 if no occurrences are found.
*/
public static int countOccurrences(@NonNull String text, @NonNull String substring) {

if (text.isEmpty() || substring.isEmpty()) {
return 0;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
package org.openrewrite.java;

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.ExecutionContext;
import org.openrewrite.java.tree.Expression;
import org.openrewrite.java.tree.J;
Expand All @@ -28,19 +27,15 @@

class JavaTemplateMatchTest implements RewriteTest {

// IMPORTANT: This test needs to stay at the top, so that the name of `JavaTemplateMatchTest$1_Equals1` matches the expectations
@DocumentExample
@SuppressWarnings("ConstantValue")
@SuppressWarnings({"ConstantValue", "ConstantConditions"})
@Test
void matchBinaryUsingCompile() {
void matchBinary() {
rewriteRun(
spec -> spec.recipe(toRecipe(() -> new JavaVisitor<>() {
// matches manually written class JavaTemplateMatchTest$1_Equals1 below
private final JavaTemplate template = JavaTemplate.compile(this, "Equals1", (Integer i) -> 1 == i).build();

@Override
public J visitBinary(J.Binary binary, ExecutionContext ctx) {
return template.matches(getCursor()) ? SearchResult.found(binary) : super.visitBinary(binary, ctx);
return JavaTemplate.matches("1 == #{any(int)}", getCursor()) ?
SearchResult.found(binary) : super.visitBinary(binary, ctx);
}
})),
java(
Expand All @@ -63,38 +58,34 @@ class Test {
));
}

@SuppressWarnings("ConstantValue")
@SuppressWarnings("ConstantConditions")
@Test
void matchBinary() {
void matchNamedParameter() {
rewriteRun(
spec -> spec.recipe(toRecipe(() -> new JavaVisitor<>() {
@Override
public J visitBinary(J.Binary binary, ExecutionContext ctx) {
return JavaTemplate.matches("1 == #{any(int)}", getCursor()) ?
return JavaTemplate.matches("#{n:any(int)} == #{n}", getCursor()) ?
SearchResult.found(binary) : super.visitBinary(binary, ctx);
}
})),
java(
"""
class Test {
boolean b1 = 1 == 2;
boolean b2 = 1 == 3;
boolean b3 = 2 == 1;
boolean b2 = 1 == 1;
}
""",
"""
class Test {
boolean b1 = /*~~>*/1 == 2;
boolean b2 = /*~~>*/1 == 3;
boolean b3 = 2 == 1;
boolean b1 = 1 == 2;
boolean b2 = /*~~>*/1 == 1;
}
"""
));
}

@SuppressWarnings("ConstantValue")
@SuppressWarnings({"ConstantValue", "ConstantConditions"})
@Test
void extractParameterUsingMatcher() {
rewriteRun(
Expand Down Expand Up @@ -532,14 +523,3 @@ class Test {
}
}

/**
* This class looks like a class which would be generated by the `rewrite-templating` annotation processor
* and is used by the test {@link JavaTemplateMatchTest#matchBinaryUsingCompile()}.
*/
@SuppressWarnings("unused")
class JavaTemplateMatchTest$1_Equals1 {
static JavaTemplate.Builder getTemplate(JavaVisitor<?> visitor) {
return JavaTemplate.builder("1 == #{any(int)}");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Copyright 2023 the original author or authors.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java;

import org.junit.jupiter.api.Test;
import org.openrewrite.ExecutionContext;
import org.openrewrite.java.tree.J;
import org.openrewrite.test.RewriteTest;

import static org.openrewrite.java.Assertions.java;
import static org.openrewrite.test.RewriteTest.toRecipe;

public class JavaTemplateNamedTest implements RewriteTest {

@Test
void replaceSingleStatement() {
rewriteRun(
spec -> spec.recipe(toRecipe(() -> new JavaVisitor<>() {
@Override
public J visitAssert(J.Assert anAssert, ExecutionContext p) {
return JavaTemplate.builder(
"""
if(#{name:any(int)} != #{}) {
#{name}++;
}"""
)
.build()
.apply(getCursor(), anAssert.getCoordinates().replace(),
((J.Binary) anAssert.getCondition()).getLeft(), "1");
}
})),
java(
"""
class Test {
int n;
void test() {
assert n == 0;
}
}
""",
"""
class Test {
int n;
void test() {
if (n != 1) {
n++;
}
}
}
"""
)
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,28 +22,49 @@

import static org.junit.jupiter.api.Assertions.assertTrue;

public class SemanticallyEqualTest {
public class SemanticallyEqualTest {

private final JavaParser javaParser = JavaParser.fromJavaVersion().build();

@Test
void compareAbstractMethods() {
assertEqualToSelf("""
abstract class A {
abstract void m();
}
""");
assertEqualToSelf(
"""
abstract class A {
abstract void m();
}
"""
);
}

@Test
void compareClassModifierLists() {
assertEqual("""
public abstract class A {
}
""", """
abstract public class A {
}
""");
assertEqual(
"""
public abstract class A {
}
""",
"""
abstract public class A {
}
"""
);
}

@Test
void compareLiterals() {
assertEqual(
"""
class A {
int n = 1;
}
""",
"""
class A {
int n = 1;
}
"""
);
}

private void assertEqualToSelf(@Language("java") String a) {
Expand Down
7 changes: 3 additions & 4 deletions rewrite-java/src/main/antlr/TemplateParameterLexer.g4
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,9 @@ lexer grammar TemplateParameterLexer;

LPAREN : '(';
RPAREN : ')';
LBRACK : '[';
RBRACK : ']';
DOT : '.';

COLON : ':';
COMMA : ',';
SPACE : ' ';

FullyQualifiedName
: 'boolean'
Expand Down Expand Up @@ -52,3 +49,5 @@ JavaLetterOrDigit
[\uD800-\uDBFF] [\uDC00-\uDFFF]
{Character.isJavaIdentifierPart(Character.toCodePoint((char)_input.LA(-2), (char)_input.LA(-1)))}?
;

S : [ \t\r\n] -> skip ;
15 changes: 14 additions & 1 deletion rewrite-java/src/main/antlr/TemplateParameterParser.g4
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,16 @@ parser grammar TemplateParameterParser;
options { tokenVocab=TemplateParameterLexer; }

matcherPattern
: matcherName LPAREN matcherParameter* RPAREN
: typedPattern
| parameterName
;

typedPattern
: (parameterName COLON)? patternType
;

patternType
: matcherName LPAREN ((matcherParameter COMMA)* matcherParameter)? RPAREN
;

matcherParameter
Expand All @@ -12,6 +21,10 @@ matcherParameter
| Number
;

parameterName
: Identifier
;

matcherName
: Identifier
;
Loading

0 comments on commit ba69707

Please sign in to comment.