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

Adjust CatchClauseOnlyRethrows to work with C# #395

Merged
merged 12 commits into from
Nov 28, 2024
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@

import org.openrewrite.ExecutionContext;
import org.openrewrite.Recipe;
import org.openrewrite.SourceFile;
import org.openrewrite.TreeVisitor;
import org.openrewrite.csharp.tree.Cs;
import org.openrewrite.internal.ListUtils;
import org.openrewrite.java.JavaIsoVisitor;
import org.openrewrite.java.tree.Expression;
Expand Down Expand Up @@ -113,6 +115,13 @@ private boolean onlyRethrows(J.Try.Catch aCatch) {
}

Expression exception = ((J.Throw) aCatch.getBody().getStatements().get(0)).getException();

// In C# an implicit rethrow is possible
if (getCursor().firstEnclosing(SourceFile.class) instanceof Cs &&
exception instanceof J.Empty) {
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
return true;
}

JavaType catchParameterType = aCatch.getParameter().getType();
if (!(catchParameterType instanceof JavaType.MultiCatch)) {
JavaType.FullyQualified catchType = TypeUtils.asFullyQualified(catchParameterType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,16 @@
package org.openrewrite.staticanalysis;

import org.junit.jupiter.api.Test;
import org.openrewrite.DocumentExample;
import org.openrewrite.*;
import org.openrewrite.csharp.tree.Cs;
import org.openrewrite.java.JavaVisitor;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.Space;
import org.openrewrite.marker.Markers;
import org.openrewrite.test.RecipeSpec;
import org.openrewrite.test.RewriteTest;

import static org.assertj.core.api.Assertions.assertThat;
import static org.openrewrite.java.Assertions.java;

@SuppressWarnings("ALL")
Expand All @@ -38,7 +44,7 @@ void rethrownButWithDifferentMessage() {
"""
import java.io.FileReader;
import java.io.IOException;

class A {
void foo() throws IOException {
try {
Expand All @@ -63,7 +69,7 @@ void catchShouldBePreservedBecauseLessSpecificCatchFollows() {
"""
import java.io.FileReader;
import java.io.IOException;

class A {
void foo() throws IOException {
try {
Expand All @@ -90,7 +96,7 @@ void catchShouldBePreservedBecauseLessSpecificCatchFollowsWithMultiCast() {
"""
import java.io.FileReader;
import java.io.IOException;

class A {
void foo() throws IOException {
try {
Expand All @@ -116,7 +122,7 @@ void tryCanBeRemoved() {
"""
import java.io.FileReader;
import java.io.IOException;

class A {
void foo() throws IOException {
try {
Expand All @@ -130,7 +136,7 @@ void foo() throws IOException {
"""
import java.io.FileReader;
import java.io.IOException;

class A {
void foo() throws IOException {
new FileReader("").read();
Expand All @@ -150,7 +156,7 @@ void tryCanBeRemovedWithMultiCatch() {
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;

class A {
void foo() throws IOException {
try {
Expand All @@ -166,16 +172,16 @@ void foo() throws IOException {
}
""",
"""
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;
class A {
void foo() throws IOException {
new FileReader("").read();
}
}
"""
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;

class A {
void foo() throws IOException {
new FileReader("").read();
}
}
"""
)
);
}
Expand All @@ -189,7 +195,7 @@ void multiCatchPreservedOnDifferentThrow() {
import java.io.FileReader;
import java.io.IOException;
import java.io.FileNotFoundException;

class A {
void foo() throws IOException {
try {
Expand All @@ -214,7 +220,7 @@ void tryShouldBePreservedBecauseFinally() {
"""
import java.io.FileReader;
import java.io.IOException;

class A {
void foo() throws IOException {
try {
Expand All @@ -230,7 +236,7 @@ void foo() throws IOException {
"""
import java.io.FileReader;
import java.io.IOException;

class A {
void foo() throws IOException {
try {
Expand All @@ -253,7 +259,7 @@ void tryShouldBePreservedBecauseResources() {
"""
import java.io.FileReader;
import java.io.IOException;

class A {
void foo() throws IOException {
try(FileReader fr = new FileReader("")) {
Expand All @@ -267,7 +273,7 @@ void foo() throws IOException {
"""
import java.io.FileReader;
import java.io.IOException;

class A {
void foo() throws IOException {
try(FileReader fr = new FileReader("")) {
Expand All @@ -288,7 +294,7 @@ void wrappingAndRethrowingIsUnchanged() {
"""
import java.io.FileReader;
import java.io.IOException;

class A {
void foo() {
try {
Expand All @@ -311,7 +317,7 @@ void loggingAndRethrowingIsUnchanged() {
"""
import java.io.FileReader;
import java.io.IOException;

class A {
void foo() throws IOException {
try {
Expand All @@ -326,4 +332,55 @@ void foo() throws IOException {
)
);
}

@Test
void verifyCsharpImplicitThrow() {
rewriteRun(
spec -> spec.recipe(Recipe.noop()),
//language=java
java(
"""
class A {
void foo() throws IllegalAccessException {
try {
throw new IllegalAccessException();
} catch (Exception e) {
throw e; // C# can rethrow the caught exception implicitly and so the `e` Identifier is removed by the inline visitor below
}
}
}"""
, spec -> spec.beforeRecipe(compUnit -> {
Cs.CompilationUnit cSharpCompUnit = (Cs.CompilationUnit) new JavaVisitor<ExecutionContext>() {
@Override
public J visitThrow(J.Throw thrown, ExecutionContext ctx) {
if (thrown.getException() instanceof J.Identifier) {
return thrown.withException(new J.Empty(Tree.randomId(), Space.EMPTY, Markers.EMPTY));
}
return thrown;
}
}.visit(JavaToCsharp.compilationUnit(compUnit), new InMemoryExecutionContext());

assertThat(cSharpCompUnit.getMembers().get(0)).isInstanceOf(J.ClassDeclaration.class);
assertThat(((J.ClassDeclaration)cSharpCompUnit.getMembers().get(0)).getBody().getStatements().get(0)).isInstanceOf(J.MethodDeclaration.class);
J.MethodDeclaration md = (J.MethodDeclaration) ((J.ClassDeclaration)cSharpCompUnit.getMembers().get(0)).getBody().getStatements().get(0);
assertThat(md.getBody().getStatements().get(0)).isInstanceOf(J.Try.class);

Cs.CompilationUnit output = (Cs.CompilationUnit) new CatchClauseOnlyRethrows().getVisitor().visit(cSharpCompUnit, new InMemoryExecutionContext());

assertThat(output.getMembers().get(0)).isInstanceOf(J.ClassDeclaration.class);
assertThat(((J.ClassDeclaration)output.getMembers().get(0)).getBody().getStatements().get(0)).isInstanceOf(J.MethodDeclaration.class);
md = (J.MethodDeclaration) ((J.ClassDeclaration)output.getMembers().get(0)).getBody().getStatements().get(0);
assertThat(md.getBody().getStatements().get(0)).isInstanceOf(J.Throw.class);
}
)
)
);
}
timtebeek marked this conversation as resolved.
Show resolved Hide resolved

public JavaVisitor<ExecutionContext> getJavaToCsharpVisitor() {
return new JavaVisitor<>() {


};
}
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
}
32 changes: 32 additions & 0 deletions src/test/java/org/openrewrite/staticanalysis/JavaToCsharp.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* 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.staticanalysis;

import org.openrewrite.csharp.tree.Cs;
import org.openrewrite.java.tree.J;
import org.openrewrite.java.tree.JRightPadded;
import org.openrewrite.java.tree.Statement;

import java.util.List;
timtebeek marked this conversation as resolved.
Show resolved Hide resolved
import java.util.stream.Collectors;

timtebeek marked this conversation as resolved.
Show resolved Hide resolved
public class JavaToCsharp {

public static Cs.CompilationUnit compilationUnit(J.CompilationUnit cu) {
return new Cs.CompilationUnit(cu.getId(), cu.getPrefix(), cu.getMarkers(), cu.getSourcePath(),
cu.getFileAttributes(), cu.getCharset().name(), cu.isCharsetBomMarked(), cu.getChecksum(), List.of(), List.of(), List.of(), cu.getClasses().stream().map(Statement.class::cast).map(cd -> JRightPadded.build(cd)).collect(Collectors.toList()), cu.getEof());
}
}