Skip to content

Commit

Permalink
Add allowCommentedBlocks property to EmptyControlStatementRule
Browse files Browse the repository at this point in the history
  • Loading branch information
bergander committed Nov 27, 2023
1 parent bdc08e4 commit c9b66c0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
Expand Up @@ -21,13 +21,25 @@
import net.sourceforge.pmd.lang.java.ast.JavaNode;
import net.sourceforge.pmd.lang.java.rule.AbstractJavaRulechainRule;
import net.sourceforge.pmd.lang.java.rule.internal.JavaRuleUtil;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;

public class EmptyControlStatementRule extends AbstractJavaRulechainRule {

private static final PropertyDescriptor<Boolean> ALLOW_COMMENTED_BLOCKS
= PropertyFactory.booleanProperty("allowCommentedBlocks")
.desc("Option for allowing empty but commented blocks. This is useful where a developer " +
"wants to have the code structure and explain why a condition does not require " +
"logic or to hold TODO comments for future work.")
.defaultValue(Boolean.FALSE)
.build();

public EmptyControlStatementRule() {
super(ASTFinallyClause.class, ASTSynchronizedStatement.class, ASTTryStatement.class, ASTDoStatement.class,
ASTBlock.class, ASTForStatement.class, ASTForeachStatement.class, ASTWhileStatement.class,
ASTIfStatement.class, ASTSwitchStatement.class, ASTInitializer.class);

definePropertyDescriptor(ALLOW_COMMENTED_BLOCKS);
}

@Override
Expand Down Expand Up @@ -145,7 +157,9 @@ public Object visit(ASTTryStatement node, Object data) {
}

private boolean isEmpty(JavaNode node) {
return node instanceof ASTBlock && node.getNumChildren() == 0
boolean allowCommentedBlocks = getProperty(ALLOW_COMMENTED_BLOCKS);

return (node instanceof ASTBlock && node.getNumChildren() == 0 && !(((ASTBlock)node).containsComment() && allowCommentedBlocks))
|| node instanceof ASTEmptyStatement;
}
}
Expand Up @@ -228,7 +228,7 @@
}
]]></code>
</test-code>

<test-code>
<description>empty initializer failure case (non static)</description>
<expected-problems>1</expected-problems>
Expand Down Expand Up @@ -502,7 +502,8 @@ public class Foo {
</test-code>

<test-code>
<description>empty if statement with comment</description>
<description>empty if statement with comment, disallow commented block</description>
<rule-property name="allowCommentedBlocks">false</rule-property>
<expected-problems>1</expected-problems>
<expected-messages>
<message>Empty if statement</message>
Expand All @@ -516,5 +517,21 @@ public class Foo {
}
}
]]></code>

</test-code>
<test-code>
<description>empty if statement with comment, allow commented block</description>
<rule-property name="allowCommentedBlocks">true</rule-property>
<expected-problems>0</expected-problems>
<code><![CDATA[
public class Foo {
void bar(int x) {
if (x == 0) {
// empty!
}
}
}
]]></code>

</test-code>
</test-data>

0 comments on commit c9b66c0

Please sign in to comment.