public class WhitespaceAroundCheck extends AbstractCheck
Checks that a token is surrounded by whitespace. Empty constructor, method, class, enum, interface, loop bodies (blocks), lambdas of the form
public MyClass() {} // empty constructor
public void func() {} // empty method
public interface Foo {} // empty interface
public class Foo {} // empty class
public enum Foo {} // empty enum
MyClass c = new MyClass() {}; // empty anonymous class
while (i = 1) {} // empty while loop
for (int i = 1; i > 1; i++) {} // empty for loop
do {} while (i = 1); // empty do-while loop
Runnable noop = () -> {}; // empty lambda
public @interface Beta {} // empty annotation type
may optionally be exempted from the policy using the allowEmptyMethods,
allowEmptyConstructors, allowEmptyTypes, allowEmptyLoops,
allowEmptyLambdas and allowEmptyCatches properties.
This check does not flag as violation double brace initialization like:
new Properties() {{
setProperty("key", "value");
}};
Parameter allowEmptyCatches allows to suppress violations when token list contains SLIST to check if beginning of block is surrounded by whitespace and catch block is empty, for example:
try {
k = 5 / i;
} catch (ArithmeticException ex) {}
With this property turned off, this raises violation because the beginning of the catch block (left curly bracket) is not separated from the end of the catch block (right curly bracket).
allowEmptyConstructors - Allow empty constructor bodies.
Type is boolean.
Default value is false.
allowEmptyMethods - Allow empty method bodies.
Type is boolean.
Default value is false.
allowEmptyTypes - Allow empty class, interface and enum bodies.
Type is boolean.
Default value is false.
allowEmptyLoops - Allow empty loop bodies.
Type is boolean.
Default value is false.
allowEmptyLambdas - Allow empty lambda bodies.
Type is boolean.
Default value is false.
allowEmptyCatches - Allow empty catch bodies.
Type is boolean.
Default value is false.
ignoreEnhancedForColon - Ignore whitespace around colon in
enhanced for loop.
Type is boolean.
Default value is true.
tokens - tokens to check
Type is java.lang.String[].
Validation type is tokenSet.
Default value is:
ASSIGN,
BAND,
BAND_ASSIGN,
BOR,
BOR_ASSIGN,
BSR,
BSR_ASSIGN,
BXOR,
BXOR_ASSIGN,
COLON,
DIV,
DIV_ASSIGN,
DO_WHILE,
EQUAL,
GE,
GT,
LAMBDA,
LAND,
LCURLY,
LE,
LITERAL_CATCH,
LITERAL_DO,
LITERAL_ELSE,
LITERAL_FINALLY,
LITERAL_FOR,
LITERAL_IF,
LITERAL_RETURN,
LITERAL_SWITCH,
LITERAL_SYNCHRONIZED,
LITERAL_TRY,
LITERAL_WHILE,
LOR,
LT,
MINUS,
MINUS_ASSIGN,
MOD,
MOD_ASSIGN,
NOT_EQUAL,
PLUS,
PLUS_ASSIGN,
QUESTION,
RCURLY,
SL,
SLIST,
SL_ASSIGN,
SR,
SR_ASSIGN,
STAR,
STAR_ASSIGN,
LITERAL_ASSERT,
TYPE_EXTENSION_AND.
To configure the check:
<module name="WhitespaceAround"/>
Example:
class Test {
public Test(){} // 2 violations, '{' is not followed and preceded by whitespace.
public static void main(String[] args) {
if (foo) { // ok
// body
}
else{ // violation
// body
}
for (int i = 1; i > 1; i++) {} // violation, '{' is not followed by whitespace.
Runnable noop = () ->{}; // 2 violations,
// '{' is not followed and preceded by whitespace.
try {
// body
} catch (Exception e){} // 2 violations,
// '{' is not followed and preceded by whitespace.
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for (char item: vowels) { // ok, because ignoreEnhancedForColon is true by default
// body
}
}
}
To configure the check for whitespace only around assignment operators:
<module name="WhitespaceAround">
<property name="tokens"
value="ASSIGN,DIV_ASSIGN,PLUS_ASSIGN,MINUS_ASSIGN,STAR_ASSIGN,
MOD_ASSIGN,SR_ASSIGN,BSR_ASSIGN,SL_ASSIGN,BXOR_ASSIGN,
BOR_ASSIGN,BAND_ASSIGN"/>
</module>
Example:
class Test {
public static void main(String[] args) {
int b=10; // violation
int c = 10; // ok
b+=10; // violation
b += 10; // ok
c*=10; // violation
c *= 10; // ok
c-=5; // violation
c -= 5; // ok
c/=2; // violation
c /= 2; // ok
c%=1; // violation
c %= 1; // ok
c>>=1; // violation
c >>= 1; // ok
c>>>=1; // violation
c >>>= 1; // ok
}
public void myFunction() {
c^=1; // violation
c ^= 1; // ok
c|=1; // violation
c |= 1; // ok
c&=1; // violation
c &= 1; // ok
c<<=1; // violation
c <<= 1; // ok
}
}
To configure the check for whitespace only around curly braces:
<module name="WhitespaceAround"> <property name="tokens" value="LCURLY,RCURLY"/> </module>
Example:
class Test {
public void myFunction() {} // violation
public void myFunction() { } // ok
}
To configure the check to allow empty method bodies:
<module name="WhitespaceAround"> <property name="allowEmptyMethods" value="true"/> </module>
Example:
class Test {
public void muFunction() {} // ok
int a=4; // 2 violations, '=' is not followed and preceded by whitespace.
}
To configure the check to allow empty constructor bodies:
<module name="WhitespaceAround"> <property name="allowEmptyConstructors" value="true"/> </module>
Example:
class Test {
public Test() {} // ok
public void muFunction() {} // violation, '{' is not followed by whitespace.
}
To configure the check to allow empty type bodies:
<module name="WhitespaceAround"> <property name="allowEmptyTypes" value="true"/> </module>
Example:
class Test {} // ok
interface testInterface{} // ok
class anotherTest {
int a=4; // 2 violations, '=' is not followed and preceded by whitespace.
}
To configure the check to allow empty loop bodies:
<module name="WhitespaceAround"> <property name="allowEmptyLoops" value="true"/> </module>
Example:
class Test {
public static void main(String[] args) {
for (int i = 100;i > 10; i--){} // ok
do {} while (i = 1); // ok
int a=4; // 2 violations, '=' is not followed and preceded by whitespace.
}
}
To configure the check to allow empty lambda bodies:
<module name="WhitespaceAround"> <property name="allowEmptyLambdas" value="true"/> </module>
Example:
class Test {
public static void main(String[] args) {
Runnable noop = () -> {}; // ok
int a=4; // 2 violations, '=' is not followed and preceded by whitespace.
}
}
To configure the check to allow empty catch bodies:
<module name="WhitespaceAround"> <property name="allowEmptyCatches" value="true"/> </module>
Example:
class Test {
public static void main(String[] args) {
int a=4; // 2 violations, '=' is not followed and preceded by whitespace.
try {
// body
} catch (Exception e){} // ok
}
}
Also, this check can be configured to ignore the colon in an enhanced for loop. The colon in an enhanced for loop is ignored by default.
To configure the check to ignore the colon:
<module name="WhitespaceAround"> <property name="ignoreEnhancedForColon" value="false" /> </module>
Example:
class Test {
public static void main(String[] args) {
int a=4; // 2 violations , '=' is not followed and preceded by whitespace.
char[] vowels = {'a', 'e', 'i', 'o', 'u'};
for (char item: vowels) { // violation, ':' is not preceded by whitespace.
// body
}
}
}
Parent is com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
ws.notFollowed
ws.notPreceded
AutomaticBean.OutputStreamOptions| Modifier and Type | Field and Description |
|---|---|
private boolean |
allowEmptyCatches
Allow empty catch bodies.
|
private boolean |
allowEmptyConstructors
Allow empty constructor bodies.
|
private boolean |
allowEmptyLambdas
Allow empty lambda bodies.
|
private boolean |
allowEmptyLoops
Allow empty loop bodies.
|
private boolean |
allowEmptyMethods
Allow empty method bodies.
|
private boolean |
allowEmptyTypes
Allow empty class, interface and enum bodies.
|
private boolean |
ignoreEnhancedForColon
Ignore whitespace around colon in
enhanced for loop.
|
static java.lang.String |
MSG_WS_NOT_FOLLOWED
A key is pointing to the warning message text in "messages.properties"
file.
|
static java.lang.String |
MSG_WS_NOT_PRECEDED
A key is pointing to the warning message text in "messages.properties"
file.
|
| Constructor and Description |
|---|
WhitespaceAroundCheck() |
| Modifier and Type | Method and Description |
|---|---|
int[] |
getAcceptableTokens()
The configurable token set.
|
int[] |
getDefaultTokens()
Returns the default token a check is interested in.
|
int[] |
getRequiredTokens()
The tokens that this check must be registered for.
|
private static boolean |
isAnonymousInnerClassEnd(int currentType,
char nextChar)
Check for "})" or "};" or "},".
|
private static boolean |
isArrayInitialization(int currentType,
int parentType)
Is array initialization.
|
private static boolean |
isColonOfCaseOrDefault(int parentType)
Whether colon belongs to cases or defaults.
|
private boolean |
isColonOfForEach(int parentType)
Whether colon belongs to for-each.
|
private boolean |
isEmptyBlock(DetailAST ast,
int parentType)
Is empty block.
|
private static boolean |
isEmptyBlock(DetailAST ast,
int parentType,
int match)
Tests if a given
DetailAST is part of an empty block. |
private boolean |
isEmptyCatch(DetailAST ast,
int parentType)
Tests if the given
DetailAst is part of an allowed empty
catch block. |
private boolean |
isEmptyCtorBlockCheckedFromRcurly(DetailAST ast)
Test if the given
DetailAST is part of an allowed empty
constructor (ctor) block checked from RCURLY. |
private boolean |
isEmptyCtorBlockCheckedFromSlist(DetailAST ast)
Test if the given
DetailAST is a part of an allowed
empty constructor checked from SLIST token. |
private boolean |
isEmptyLambda(DetailAST ast,
int parentType)
Test if the given
DetailAST is part of an allowed empty
lambda block. |
private boolean |
isEmptyLoop(DetailAST ast,
int parentType)
Checks if loop is empty.
|
private boolean |
isEmptyMethodBlock(DetailAST ast,
int parentType)
Test if the given
DetailAST is part of an allowed empty
method block. |
private static boolean |
isEmptyType(DetailAST ast)
Test if the given
DetailAST is part of an empty block. |
private boolean |
isNotRelevantSituation(DetailAST ast,
int currentType)
Is ast not a target of Check.
|
private static boolean |
isPartOfDoubleBraceInitializerForNextToken(DetailAST ast)
Check if given ast is part of double brace initializer and if it
should omit checking if next token is separated by whitespace.
|
private static boolean |
isPartOfDoubleBraceInitializerForPreviousToken(DetailAST ast)
Check if given ast is part of double brace initializer and if it
should omit checking if previous token is separated by whitespace.
|
void |
setAllowEmptyCatches(boolean allow)
Setter to allow empty catch bodies.
|
void |
setAllowEmptyConstructors(boolean allow)
Setter to allow empty constructor bodies.
|
void |
setAllowEmptyLambdas(boolean allow)
Setter to allow empty lambda bodies.
|
void |
setAllowEmptyLoops(boolean allow)
Setter to allow empty loop bodies.
|
void |
setAllowEmptyMethods(boolean allow)
Setter to allow empty method bodies.
|
void |
setAllowEmptyTypes(boolean allow)
Setter to allow empty class, interface and enum bodies.
|
void |
setIgnoreEnhancedForColon(boolean ignore)
Setter to ignore whitespace around colon in
enhanced for loop.
|
private boolean |
shouldCheckSeparationFromNextToken(DetailAST ast,
char nextChar)
Check if it should be checked if next token is separated from current by
whitespace.
|
private static boolean |
shouldCheckSeparationFromPreviousToken(DetailAST ast)
Check if it should be checked if previous token is separated from current by
whitespace.
|
void |
visitToken(DetailAST ast)
Called to process a token.
|
beginTree, clearViolations, destroy, finishTree, getFileContents, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokensfinishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityconfigure, contextualize, getConfiguration, setupChildpublic static final java.lang.String MSG_WS_NOT_PRECEDED
public static final java.lang.String MSG_WS_NOT_FOLLOWED
private boolean allowEmptyConstructors
private boolean allowEmptyMethods
private boolean allowEmptyTypes
private boolean allowEmptyLoops
private boolean allowEmptyLambdas
private boolean allowEmptyCatches
private boolean ignoreEnhancedForColon
public WhitespaceAroundCheck()
public int[] getDefaultTokens()
AbstractCheckgetDefaultTokens in class AbstractCheckTokenTypespublic int[] getAcceptableTokens()
AbstractCheckgetAcceptableTokens in class AbstractCheckTokenTypespublic int[] getRequiredTokens()
AbstractCheckgetRequiredTokens in class AbstractCheckTokenTypespublic void setAllowEmptyMethods(boolean allow)
allow - true to allow empty method bodies.public void setAllowEmptyConstructors(boolean allow)
allow - true to allow empty constructor bodies.public void setIgnoreEnhancedForColon(boolean ignore)
ignore - true to ignore enhanced for colon.public void setAllowEmptyTypes(boolean allow)
allow - true to allow empty type bodies.public void setAllowEmptyLoops(boolean allow)
allow - true to allow empty loops bodies.public void setAllowEmptyLambdas(boolean allow)
allow - true to allow empty lambda expressions.public void setAllowEmptyCatches(boolean allow)
allow - true to allow empty catch blocks.public void visitToken(DetailAST ast)
AbstractCheckvisitToken in class AbstractCheckast - the token to processprivate boolean isNotRelevantSituation(DetailAST ast, int currentType)
ast - astcurrentType - type of astprivate static boolean shouldCheckSeparationFromPreviousToken(DetailAST ast)
ast - current AST.private boolean shouldCheckSeparationFromNextToken(DetailAST ast, char nextChar)
ast - current AST.nextChar - next character.private static boolean isAnonymousInnerClassEnd(int currentType, char nextChar)
currentType - tokennextChar - next symbolprivate boolean isEmptyBlock(DetailAST ast, int parentType)
ast - astparentType - parentprivate static boolean isEmptyBlock(DetailAST ast, int parentType, int match)
DetailAST is part of an empty block.
An example empty block might look like the following
public void myMethod(int val) {}
In the above, the method body is an empty block ("{}").ast - the DetailAST to test.parentType - the token type of ast's parent.match - the parent token type we're looking to match.true if ast makes up part of an
empty block contained under a match token type
node.private static boolean isColonOfCaseOrDefault(int parentType)
parentType - parentprivate boolean isColonOfForEach(int parentType)
parentType - parentprivate static boolean isArrayInitialization(int currentType, int parentType)
currentType - current tokenparentType - parent tokenprivate boolean isEmptyMethodBlock(DetailAST ast, int parentType)
DetailAST is part of an allowed empty
method block.ast - the DetailAST to test.parentType - the token type of ast's parent.true if ast makes up part of an
allowed empty method block.private boolean isEmptyCtorBlockCheckedFromRcurly(DetailAST ast)
DetailAST is part of an allowed empty
constructor (ctor) block checked from RCURLY.ast - the DetailAST to test.true if ast makes up part of an
allowed empty constructor block.private boolean isEmptyCtorBlockCheckedFromSlist(DetailAST ast)
DetailAST is a part of an allowed
empty constructor checked from SLIST token.ast - the DetailAST to test.true if ast makes up part of an
empty constructor block.private boolean isEmptyLoop(DetailAST ast, int parentType)
ast - ast the DetailAST to test.parentType - the token type of ast's parent.true if ast makes up part of an
allowed empty loop block.private boolean isEmptyLambda(DetailAST ast, int parentType)
DetailAST is part of an allowed empty
lambda block.ast - the DetailAST to test.parentType - the token type of ast's parent.true if ast makes up part of an
allowed empty lambda block.private boolean isEmptyCatch(DetailAST ast, int parentType)
DetailAst is part of an allowed empty
catch block.ast - the DetailAst to test.parentType - the token type of ast's parenttrue if ast makes up part of an
allowed empty catch block.private static boolean isEmptyType(DetailAST ast)
DetailAST is part of an empty block.
An example empty block might look like the following
class Foo {}ast - ast the DetailAST to test.true if ast makes up part of an
empty block contained under a match token type
node.private static boolean isPartOfDoubleBraceInitializerForPreviousToken(DetailAST ast)
ast - ast to checkprivate static boolean isPartOfDoubleBraceInitializerForNextToken(DetailAST ast)
ast - ast to checkCopyright © 2001-2022. All Rights Reserved.