Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaTemplate matching on parameterized types #3963

Merged
merged 12 commits into from
Feb 2, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@

public class JavaTemplateMatchTest implements RewriteTest {


@Test
void nonJavaCode() {
rewriteRun(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -370,9 +370,12 @@ void matchCompatibleTypes() {

@Override
public J visitExpression(Expression expression, ExecutionContext ctx) {
return expression.getMarkers().findFirst(SearchResult.class).isEmpty() && template.matches(getCursor()) ? SearchResult.found(expression) : super.visitExpression(expression, ctx);
if (template.matches(getCursor())) {
return SearchResult.found(expression);
}
return super.visitExpression(expression, ctx);
}
})),
}).withMaxCycles(1)),
java(
"""
class Test {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ public J.Assignment visitAssignment(J.Assignment assignment, ExecutionContext p)
((J.Literal) assignment.getAssignment()).getValue().equals(1)) {
return JavaTemplate.builder("value = 0")
.contextSensitive()
.doBeforeParseTemplate(System.out::println)
.build()
.apply(getCursor(), assignment.getCoordinates().replace());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/*
* Copyright 2024 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.Cursor;
import org.openrewrite.ExecutionContext;
import org.openrewrite.java.tree.NameTree;
import org.openrewrite.marker.SearchResult;
import org.openrewrite.test.RewriteTest;

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

public class JavaTemplateTest8Test implements RewriteTest {

@Test
void parameterizedMatch() {
JavaTemplate template = JavaTemplate.builder("#{any(java.util.List<String>)}")
.build();

rewriteRun(
spec -> spec.recipe(toRecipe(() -> new JavaIsoVisitor<>() {
@Override
public <N extends NameTree> N visitTypeName(N nameTree, ExecutionContext ctx) {
// the cursor points at the parent when `visitTypeName()` is called
if (template.matches(new Cursor(getCursor(), nameTree))) {
return SearchResult.found(nameTree);
}
return super.visitTypeName(nameTree, ctx);
}
})),
java(
"""
import java.util.List;
class Test {
List<Object> o;
List<String> s;
List<Number> n;
List<Integer> i;
List<java.lang.Object> qo;
List<java.lang.String> qs;
List<java.lang.Number> qn;
List<java.lang.Integer> qi;
}
""",
"""
import java.util.List;
class Test {
List<Object> o;
/*~~>*/List<String> s;
List<Number> n;
List<Integer> i;
List<java.lang.Object> qo;
/*~~>*/List<java.lang.String> qs;
List<java.lang.Number> qn;
List<java.lang.Integer> qi;
}
"""
)
);
}

@Test
void parameterizedMatchWithBounds() {
JavaTemplate template = JavaTemplate.builder("#{any(java.util.List<? extends java.lang.Number>)}")
.build();

rewriteRun(
spec -> spec.recipe(toRecipe(() -> new JavaIsoVisitor<>() {
@Override
public <N extends NameTree> N visitTypeName(N nameTree, ExecutionContext ctx) {
// the cursor points at the parent when `visitTypeName()` is called
if (template.matches(new Cursor(getCursor(), nameTree))) {
return SearchResult.found(nameTree);
}
return super.visitTypeName(nameTree, ctx);
}
})),
java(
"""
import java.util.List;
class Test {
List<Object> o;
List<String> s;
List<Number> n;
List<Integer> i;
List<java.lang.Object> qo;
List<java.lang.String> qs;
List<java.lang.Number> qn;
List<java.lang.Integer> qi;
}
""",
"""
import /*~~>*/java.util.List;
class Test {
List<Object> o;
List<String> s;
/*~~>*/List<Number> n;
/*~~>*/List<Integer> i;
List<java.lang.Object> qo;
List<java.lang.String> qs;
/*~~>*/List<java.lang.Number> qn;
/*~~>*/List<java.lang.Integer> qi;
}
"""
)
);
}
}
7 changes: 6 additions & 1 deletion rewrite-java/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ plugins {
id("org.openrewrite.build.language-library")
}

val antlrGeneration by configurations.creating {
extendsFrom(configurations.implementation.get())
}

tasks.register<JavaExec>("generateAntlrSources") {
mainClass.set("org.antlr.v4.Tool")

Expand All @@ -11,7 +15,7 @@ tasks.register<JavaExec>("generateAntlrSources") {
"-visitor"
) + fileTree("src/main/antlr").matching { include("**/*.g4") }.map { it.path }

classpath = sourceSets["main"].runtimeClasspath
classpath = antlrGeneration
}

dependencies {
Expand All @@ -22,6 +26,7 @@ dependencies {
api("io.micrometer:micrometer-core:1.9.+")
api("org.jetbrains:annotations:latest.release")

antlrGeneration("org.antlr:antlr4:4.11.1")
implementation("org.antlr:antlr4-runtime:4.11.1")
compileOnly("com.puppycrawl.tools:checkstyle:9.+") { // Pinned to 9.+ because 10.x does not support Java 8: https://checkstyle.sourceforge.io/#JRE_and_JDK
isTransitive = false
Expand Down
8 changes: 8 additions & 0 deletions rewrite-java/src/main/antlr/TemplateParameterLexer.g4
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ RPAREN : ')';
DOT : '.';
COLON : ':';
COMMA : ',';
LBRACK : '<';
RBRACK : '>';
WILDCARD : '?';

Variance
: 'extends'
| 'super'
;

FullyQualifiedName
: 'boolean'
Expand Down
15 changes: 11 additions & 4 deletions rewrite-java/src/main/antlr/TemplateParameterLexer.tokens
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,19 @@ RPAREN=2
DOT=3
COLON=4
COMMA=5
FullyQualifiedName=6
Number=7
Identifier=8
S=9
LBRACK=6
RBRACK=7
WILDCARD=8
Variance=9
FullyQualifiedName=10
Number=11
Identifier=12
S=13
'('=1
')'=2
'.'=3
':'=4
','=5
'<'=6
'>'=7
'?'=8
21 changes: 16 additions & 5 deletions rewrite-java/src/main/antlr/TemplateParameterParser.g4
Original file line number Diff line number Diff line change
Expand Up @@ -12,19 +12,30 @@ typedPattern
;

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

matcherParameter
: FullyQualifiedName
| Identifier
| Number
type
: typeName (LBRACK (typeParameter COMMA)* typeParameter RBRACK)?
;

typeParameter
: variance? type
;

variance
: WILDCARD Variance
;

parameterName
: Identifier
;

typeName
: FullyQualifiedName
| Identifier
;

matcherName
: Identifier
;
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
package org.openrewrite.java;

import lombok.Getter;
import lombok.Value;
import lombok.experimental.NonFinal;
import org.openrewrite.Cursor;
Expand All @@ -33,23 +34,20 @@

@SuppressWarnings("unused")
public class JavaTemplate implements SourceTemplate<J, JavaCoordinates> {
@Getter
private final String code;
private final int parameterCount;

private final Consumer<String> onAfterVariableSubstitution;
private final JavaTemplateParser templateParser;

private JavaTemplate(boolean contextSensitive, JavaParser.Builder<?, ?> javaParser, String code, Set<String> imports,
Consumer<String> onAfterVariableSubstitution, Consumer<String> onBeforeParseTemplate) {
this.code = code;
this.onAfterVariableSubstitution = onAfterVariableSubstitution;
this.parameterCount = StringUtils.countOccurrences(code, "#{");
int parameterCount = StringUtils.countOccurrences(code, "#{");
this.templateParser = new JavaTemplateParser(contextSensitive, javaParser, onAfterVariableSubstitution, onBeforeParseTemplate, imports);
}

public String getCode() {
return code;
}

@Override
@SuppressWarnings("unchecked")
public <J2 extends J> J2 apply(Cursor scope, JavaCoordinates coordinates, Object... parameters) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import org.openrewrite.internal.lang.Nullable;
import org.openrewrite.java.internal.grammar.TemplateParameterLexer;
import org.openrewrite.java.internal.grammar.TemplateParameterParser;
import org.openrewrite.java.internal.grammar.TemplateParameterParser.TypedPatternContext;
import org.openrewrite.java.internal.template.TypeParameter;
import org.openrewrite.java.search.SemanticallyEqual;
import org.openrewrite.java.tree.*;
import org.openrewrite.marker.Marker;
Expand Down Expand Up @@ -93,16 +95,17 @@ public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
throw new IllegalArgumentException("The parameter " + paramName + " must be defined before it is referenced.");
}
} else {
TemplateParameterParser.TypedPatternContext typedPattern = ctx.typedPattern();
s = typedParameter(key, typedPattern);
TypedPatternContext typedPattern = ctx.typedPattern();
JavaType type = typedParameter(key, typedPattern);
s = TypeUtils.toString(type);

String name = null;
if (typedPattern.parameterName() != null) {
name = typedPattern.parameterName().Identifier().getText();
typedPatternByName.put(name, s);
}

Markers markers = Markers.build(Collections.singleton(new TemplateParameter(randomId(), s, name)));
Markers markers = Markers.build(Collections.singleton(new TemplateParameter(randomId(), type, name)));
parameters.add(new J.Empty(randomId(), Space.EMPTY, markers));
}
} else {
Expand All @@ -120,24 +123,10 @@ public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol,
return parameters.toArray(new J[0]);
}

private static String typedParameter(String key, TemplateParameterParser.TypedPatternContext typedPattern) {
private static JavaType typedParameter(String key, TypedPatternContext typedPattern) {
String matcherName = typedPattern.patternType().matcherName().Identifier().getText();
List<TemplateParameterParser.MatcherParameterContext> params = typedPattern.patternType().matcherParameter();

if ("any".equals(matcherName)) {
String fqn;

if (params.size() == 1) {
if (params.get(0).Identifier() != null) {
fqn = params.get(0).Identifier().getText();
} else {
fqn = params.get(0).FullyQualifiedName().getText();
}
} else {
fqn = "java.lang.Object";
}

return fqn.replace("$", ".");
return TypeParameter.toFullyQualifiedName(typedPattern.patternType().type());
} else {
throw new IllegalArgumentException("Invalid template matcher '" + key + "'");
}
Expand All @@ -159,7 +148,7 @@ private static TemplateMatchResult matchTemplate(J templateTree, Cursor cursor)
@With
private static class TemplateParameter implements Marker {
UUID id;
String typeName;
JavaType type;

@Nullable
String name;
Expand All @@ -174,21 +163,25 @@ public JavaTemplateSemanticallyEqualVisitor() {
}

private boolean matchTemplateParameterPlaceholder(J.Empty empty, J j) {
if (j instanceof TypedTree && !(j instanceof J.Primitive)) {
if (j instanceof TypedTree) {
if (j instanceof J.Primitive || j instanceof J.Identifier && ((J.Identifier) j).getFieldType() == null) {
// don't match types, only expressions
return false;
}
TemplateParameter marker = (TemplateParameter) empty.getMarkers().getMarkers().get(0);

if (marker.name != null) {
for (Map.Entry<J, String> matchedParameter : matchedParameters.entrySet()) {
if (matchedParameter.getValue().equals(marker.name)) {
if(!SemanticallyEqual.areEqual(matchedParameter.getKey(), j)) {
if (!SemanticallyEqual.areEqual(matchedParameter.getKey(), j)) {
return false;
}
}
}
}

if ("java.lang.Object".equals(marker.typeName) ||
TypeUtils.isAssignableTo(marker.typeName, ((TypedTree) j).getType())) {
if (TypeUtils.isObject(marker.type) ||
TypeUtils.isAssignableTo(marker.type, ((TypedTree) j).getType())) {
registerMatch(j, marker.name);
return true;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2023 the original author or authors.
* Copyright 2024 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.
Expand Down
Loading
Loading