|
17 | 17 | */ |
18 | 18 | package org.greencodeinitiative.creedengo.java.checks; |
19 | 19 |
|
| 20 | +import java.util.ArrayDeque; |
20 | 21 | import java.util.ArrayList; |
21 | | -import java.util.Arrays; |
22 | 22 | import java.util.Deque; |
23 | | -import java.util.LinkedList; |
24 | 23 | import java.util.List; |
25 | 24 |
|
| 25 | +import javax.annotation.Nonnull; |
26 | 26 | import javax.annotation.ParametersAreNonnullByDefault; |
27 | 27 |
|
28 | 28 | import org.sonar.check.Rule; |
29 | 29 | import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; |
30 | 30 | import org.sonar.plugins.java.api.JavaFileScannerContext; |
31 | | -import org.sonar.plugins.java.api.JavaVersion; |
32 | 31 | import org.sonar.plugins.java.api.tree.NewClassTree; |
33 | 32 | import org.sonar.plugins.java.api.tree.Tree; |
34 | 33 | import org.sonar.plugins.java.api.tree.TryStatementTree; |
35 | 34 | import org.sonarsource.analyzer.commons.annotations.DeprecatedRuleKey; |
36 | 35 |
|
37 | | - |
| 36 | +/** |
| 37 | + * This rule checks that objects implementing AutoCloseable interface are properly managed |
| 38 | + * using try-with-resources statement instead of try-finally blocks. |
| 39 | + * <p> |
| 40 | + * Try-with-resources ensures proper resource management and reduces the risk of resource leaks. |
| 41 | + * It also reduces boilerplate code and improves code readability. |
| 42 | + * <p> |
| 43 | + * From an environmental perspective, proper resource management prevents resource leaks |
| 44 | + * which can lead to increased memory consumption and unnecessary CPU cycles. |
| 45 | + * |
| 46 | + * @see <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html">Try-with-resources</a> |
| 47 | + */ |
38 | 48 | @Rule(key = "GCI79") |
39 | 49 | @DeprecatedRuleKey(repositoryKey = "ecocode-java", ruleKey = "EC79") |
40 | 50 | @DeprecatedRuleKey(repositoryKey = "greencodeinitiative-java", ruleKey = "S79") |
41 | 51 | public class FreeResourcesOfAutoCloseableInterface extends IssuableSubscriptionVisitor { |
42 | | - private final Deque<TryStatementTree> withinTry = new LinkedList<>(); |
43 | | - private final Deque<List<Tree>> toReport = new LinkedList<>(); |
| 52 | + |
| 53 | + /** |
| 54 | + * Stack to track nested try statements while traversing the AST |
| 55 | + */ |
| 56 | + private final Deque<TryStatementContext> tryStack = new ArrayDeque<>(); |
44 | 57 |
|
45 | 58 | private static final String JAVA_LANG_AUTOCLOSEABLE = "java.lang.AutoCloseable"; |
46 | | - protected static final String MESSAGE_RULE = "try-with-resources Statement needs to be implemented for any object that implements the AutoClosable interface."; |
| 59 | + protected static final String MESSAGE_RULE = "try-with-resources Statement needs to be implemented for any object that implements the AutoCloseable interface."; |
47 | 60 |
|
48 | 61 | @Override |
49 | 62 | @ParametersAreNonnullByDefault |
50 | 63 | public void leaveFile(JavaFileScannerContext context) { |
51 | | - withinTry.clear(); |
52 | | - toReport.clear(); |
| 64 | + tryStack.clear(); |
53 | 65 | } |
54 | 66 |
|
55 | 67 | @Override |
| 68 | + @Nonnull |
56 | 69 | public List<Tree.Kind> nodesToVisit() { |
57 | | - return Arrays.asList(Tree.Kind.TRY_STATEMENT, Tree.Kind.NEW_CLASS); |
| 70 | + return List.of(Tree.Kind.TRY_STATEMENT, Tree.Kind.NEW_CLASS); |
58 | 71 | } |
59 | 72 |
|
60 | 73 | @Override |
61 | | - public void visitNode(Tree tree) { |
| 74 | + public void visitNode(@Nonnull Tree tree) { |
62 | 75 | if (tree.is(Tree.Kind.TRY_STATEMENT)) { |
63 | | - withinTry.push((TryStatementTree) tree); |
64 | | - if (withinTry.size() != toReport.size()) { |
65 | | - toReport.push(new ArrayList<>()); |
66 | | - } |
67 | | - } |
68 | | - if (tree.is(Tree.Kind.NEW_CLASS) && ((NewClassTree) tree).symbolType().isSubtypeOf(JAVA_LANG_AUTOCLOSEABLE) && withinStandardTryWithFinally()) { |
69 | | - assert toReport.peek() != null; |
70 | | - toReport.peek().add(tree); |
| 76 | + handleTryStatement((TryStatementTree) tree); |
| 77 | + } else if (tree.is(Tree.Kind.NEW_CLASS)) { |
| 78 | + handleNewClass((NewClassTree) tree); |
71 | 79 | } |
72 | 80 | } |
73 | 81 |
|
74 | 82 | @Override |
75 | | - public void leaveNode(Tree tree) { |
| 83 | + public void leaveNode(@Nonnull Tree tree) { |
76 | 84 | if (tree.is(Tree.Kind.TRY_STATEMENT)) { |
77 | | - List<Tree> secondaryTrees = toReport.pop(); |
78 | | - if (!secondaryTrees.isEmpty()) { |
79 | | - reportIssue(tree, MESSAGE_RULE); |
| 85 | + leaveTryStatement(); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Handle entering a try statement by pushing it onto the stack |
| 91 | + */ |
| 92 | + private void handleTryStatement(@Nonnull TryStatementTree tryStatement) { |
| 93 | + tryStack.push(new TryStatementContext(tryStatement)); |
| 94 | + } |
| 95 | + |
| 96 | + /** |
| 97 | + * Handle leaving a try statement by popping it from the stack and reporting issues if needed |
| 98 | + */ |
| 99 | + private void leaveTryStatement() { |
| 100 | + if (!tryStack.isEmpty()) { |
| 101 | + TryStatementContext context = tryStack.pop(); |
| 102 | + if (!context.autoCloseableInstances.isEmpty()) { |
| 103 | + reportIssue(context.tryStatement, MESSAGE_RULE); |
| 104 | + } |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + /** |
| 109 | + * Handle new class instantiation to detect AutoCloseable objects |
| 110 | + * that are created inside a try-finally block (without try-with-resources) |
| 111 | + */ |
| 112 | + private void handleNewClass(@Nonnull NewClassTree newClass) { |
| 113 | + // Check if the new instance is an AutoCloseable |
| 114 | + if (!newClass.symbolType().isSubtypeOf(JAVA_LANG_AUTOCLOSEABLE)) { |
| 115 | + return; |
| 116 | + } |
| 117 | + |
| 118 | + // Check if we are inside a non-compliant try statement |
| 119 | + if (isInNonCompliantTry()) { |
| 120 | + TryStatementContext context = tryStack.peek(); |
| 121 | + if (context != null) { |
| 122 | + context.autoCloseableInstances.add(newClass); |
80 | 123 | } |
81 | 124 | } |
82 | 125 | } |
83 | 126 |
|
84 | | - private boolean withinStandardTryWithFinally() { |
85 | | - if (withinTry.isEmpty() || !withinTry.peek().resourceList().isEmpty()) return false; |
86 | | - assert withinTry.peek() != null; |
87 | | - return withinTry.peek().finallyBlock() != null; |
| 127 | + /** |
| 128 | + * Check if we are currently inside a try statement that: |
| 129 | + * - Does NOT use try-with-resources (no resource list) |
| 130 | + * - Has a finally block (indicating manual resource management) |
| 131 | + * |
| 132 | + * @return true if inside a non-compliant try statement |
| 133 | + */ |
| 134 | + private boolean isInNonCompliantTry() { |
| 135 | + if (tryStack.isEmpty()) { |
| 136 | + return false; |
| 137 | + } |
| 138 | + |
| 139 | + TryStatementTree currentTry = tryStack.peek().tryStatement; |
| 140 | + |
| 141 | + // If try-with-resources is already used, it's compliant |
| 142 | + if (!currentTry.resourceList().isEmpty()) { |
| 143 | + return false; |
| 144 | + } |
| 145 | + |
| 146 | + // If there's a finally block, it suggests manual resource management |
| 147 | + return currentTry.finallyBlock() != null; |
88 | 148 | } |
89 | 149 |
|
90 | | - public boolean isCompatibleWithJavaVersion(JavaVersion version) { |
91 | | - return version.isJava7Compatible(); |
| 150 | + /** |
| 151 | + * Context class to track information about a try statement during AST traversal |
| 152 | + */ |
| 153 | + private static class TryStatementContext { |
| 154 | + final TryStatementTree tryStatement; |
| 155 | + final List<Tree> autoCloseableInstances; |
| 156 | + |
| 157 | + TryStatementContext(@Nonnull TryStatementTree tryStatement) { |
| 158 | + this.tryStatement = tryStatement; |
| 159 | + this.autoCloseableInstances = new ArrayList<>(); |
| 160 | + } |
92 | 161 | } |
93 | 162 | } |
0 commit comments