Skip to content

Commit

Permalink
Retain prefix from removed parentheses
Browse files Browse the repository at this point in the history
Fixes #307
  • Loading branch information
timtebeek committed Jul 15, 2024
1 parent b1b7116 commit ad28bb1
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,7 @@ public <T extends J> J visitParentheses(J.Parentheses<T> parens, Integer executi
if (parens.getTree() instanceof J.TypeCast) {
J replacement = replacements.processTypeCast((J.TypeCast) parens.getTree(), getCursor());
if (replacement != null) {
return replacement;
return replacement.withPrefix(parens.getPrefix());
}
}
return super.visitParentheses(parens, executionContext);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -976,4 +976,65 @@ String test(Object o) {
);
}
}

@Nested
class Throws {
@Test
void throwsException() {
rewriteRun(
//language=java
java(
"""
class A {
void test(Throwable t) {
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
}
}
}
""",
"""
class A {
void test(Throwable t) {
if (t instanceof RuntimeException exception) {
throw exception;
}
}
}
"""
)
);
}

@Test
@Issue("https://github.com/openrewrite/rewrite-static-analysis/issues/307")
void throwsExceptionWithExtraParentheses() {
rewriteRun(
//language=java
java(
"""
class A {
void test(Throwable t) {
if (t instanceof Exception) {
// Extra parentheses trips up the replacement
throw ((Exception) t);
}
}
}
""",
"""
class A {
void test(Throwable t) {
if (t instanceof Exception exception) {
// Extra parentheses trips up the replacement
throw exception;
}
}
}
"""
)
);
}

}
}

0 comments on commit ad28bb1

Please sign in to comment.