Skip to content

Commit 2d6bb09

Browse files
SONARJAVA-4436 Fix FP on S2095 when using @lombok.Cleanup (#4957)
Co-authored-by: Dorian Burihabwa <75226315+dorian-burihabwa-sonarsource@users.noreply.github.com>
1 parent 565282b commit 2d6bb09

3 files changed

Lines changed: 47 additions & 1 deletion

File tree

java-symbolic-execution/java-symbolic-execution-plugin/src/main/java/org/sonar/java/se/checks/UnclosedResourcesCheck.java

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -474,11 +474,21 @@ private void closeResource(@Nullable final SymbolicValue target) {
474474
@Override
475475
public void visitIdentifier(IdentifierTree tree) {
476476
// close resource as soon as it is encountered in the resource declaration
477-
if (isWithinTryHeader(tree)) {
477+
// or if it is annotated with @lombok.Cleanup
478+
if (isWithinTryHeader(tree) || isAnnotatedLombokCleanup(tree)) {
478479
Symbol symbol = tree.symbol();
479480
closeResource(programState.getValue(symbol));
480481
}
481482
}
483+
484+
private static boolean isAnnotatedLombokCleanup(IdentifierTree tree) {
485+
return tree
486+
.symbol()
487+
.metadata()
488+
.annotations()
489+
.stream()
490+
.anyMatch(annotation -> annotation.symbol().type().fullyQualifiedName().endsWith("Cleanup"));
491+
}
482492
}
483493

484494
private class PostStatementVisitor extends CheckerTreeNodeVisitor {
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import java.io.FileInputStream;
2+
import java.io.IOException;
3+
import java.io.InputStream;
4+
import lombok.Cleanup;
5+
6+
class UnclosedResourcesLombokCheck {
7+
public void fullyQualified(String fileName) throws IOException {
8+
@lombok.Cleanup
9+
InputStream in = new FileInputStream(fileName);
10+
in.read();
11+
}
12+
13+
public void annotated(String fileName) throws IOException {
14+
@Cleanup
15+
InputStream in = new FileInputStream(fileName);
16+
in.read();
17+
}
18+
}

java-symbolic-execution/java-symbolic-execution-plugin/src/test/java/org/sonar/java/se/checks/UnclosedResourcesCheckTest.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,24 @@ void test() {
3333
.verifyIssues();
3434
}
3535

36+
@Test
37+
void doesNotRaiseOnLombokCleanupAnnotatedVariable() {
38+
SECheckVerifier.newVerifier()
39+
.onFile("src/test/files/se/UnclosedResourcesLombokCheck.java")
40+
.withCheck(new UnclosedResourcesCheck())
41+
.withClassPath(SETestUtils.CLASS_PATH)
42+
.verifyNoIssues();
43+
}
44+
45+
@Test
46+
void doesNotRaiseOnLombokCleanupAnnotatedVariableNoSemantic() {
47+
SECheckVerifier.newVerifier()
48+
.onFile("src/test/files/se/UnclosedResourcesLombokCheck.java")
49+
.withCheck(new UnclosedResourcesCheck())
50+
.withoutSemantic()
51+
.verifyNoIssues();
52+
}
53+
3654
@Test
3755
void jdbcTests() {
3856
SECheckVerifier.newVerifier()

0 commit comments

Comments
 (0)