EmptyLineSeparator: false positive duplicate violation when multiple enum constants share a line
I have read check documentation: https://checkstyle.org/checks/whitespace/emptylineseparator.html I have downloaded the latest checkstyle from: https://checkstyle.org/cmdline.html#Download_and_Run I have executed the cli and showed it below, as cli describes the problem better than 1,000 words
/var/tmp $ javac Test.java
/var/tmp $ cat config.xml
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"
"https://checkstyle.org/dtds/configuration_1_3.dtd">
<module name="Checker">
<module name="TreeWalker">
<module name="EmptyLineSeparator">
<property name="tokens" value="ENUM_CONSTANT_DEF"/>
<property name="allowMultipleEmptyLines" value="false"/>
</module>
</module>
</module>
/var/tmp $ cat Test.java
public class Test {
enum Numbers {
ONE,
TWO, THREE;
}
}
/var/tmp $ RUN_LOCALE="-Duser.language=en -Duser.country=US"
/var/tmp $ java $RUN_LOCALE -jar checkstyle-14.3.0-all.jar -c config.xml Test.java
Starting audit...
[WARN] /var/tmp/Test.java:6:9: 'ENUM_CONSTANT_DEF' has more than 1 empty lines before. [EmptyLineSeparator]
[WARN] /var/tmp/Test.java:6:14: 'ENUM_CONSTANT_DEF' has more than 1 empty lines before. [EmptyLineSeparator]
Audit done.Describe what you expect in detail.
Only one violation should be reported for line 6 on TWO (the first constant on that line):
[WARN] /var/tmp/Test.java:6:9: 'ENUM_CONSTANT_DEF' has more than 1 empty lines before. [EmptyLineSeparator]THREE is placed on the same line as TWO (a shared line) and should not trigger a duplicate violation for the empty lines preceding that line.
Root Cause
In EmptyLineSeparatorCheck.java:
private static boolean isEnumConstantOnSharedLine(DetailAST ast) {
boolean result = false;
final DetailAST objectBlock = ast.getParent();
if (objectBlock.getParent().getLineNo() == ast.getLineNo()) {
result = true;
}
else {
final DetailAST firstConstant =
objectBlock.findFirstToken(TokenTypes.ENUM_CONSTANT_DEF);
if (firstConstant.getLineNo() == ast.getLineNo()
&& firstConstant.getColumnNo() < ast.getColumnNo()) {
result = true;
}
}
return result;
}firstConstant is obtained via objectBlock.findFirstToken(TokenTypes.ENUM_CONSTANT_DEF), which always returns the first constant in the enum declaration (e.g. ONE on line 3).
When multiple enum constants share any subsequent line (such as TWO, THREE; on line 6):
firstConstantisONE(line 3).- For
THREE(line 6),firstConstant.getLineNo() == ast.getLineNo()is3 == 6->false. isEnumConstantOnSharedLine(THREE)evaluates tofalse.- Checkstyle logs a duplicate violation on
THREE.
Source: checkstyle/checkstyle