Class WhitespaceAroundCheck
- All Implemented Interfaces:
Configurable,Contextualizable
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).
-
Property
allowEmptyConstructors- Allow empty constructor bodies. Type isboolean. Default value isfalse. -
Property
allowEmptyMethods- Allow empty method bodies. Type isboolean. Default value isfalse. -
Property
allowEmptyTypes- Allow empty class, interface and enum bodies. Type isboolean. Default value isfalse. -
Property
allowEmptyLoops- Allow empty loop bodies. Type isboolean. Default value isfalse. -
Property
allowEmptyLambdas- Allow empty lambda bodies. Type isboolean. Default value isfalse. -
Property
allowEmptyCatches- Allow empty catch bodies. Type isboolean. Default value isfalse. -
Property
ignoreEnhancedForColon- Ignore whitespace around colon in enhanced for loop. Type isboolean. Default value istrue. -
Property
tokens- tokens to check Type isjava.lang.String[]. Validation type istokenSet. 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
- Since:
- 3.0
-
Nested Class Summary
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
AutomaticBean.OutputStreamOptions -
Field Summary
FieldsModifier and TypeFieldDescriptionprivate booleanAllow empty catch bodies.private booleanAllow empty constructor bodies.private booleanAllow empty lambda bodies.private booleanAllow empty loop bodies.private booleanAllow empty method bodies.private booleanAllow empty class, interface and enum bodies.private booleanIgnore whitespace around colon in enhanced for loop.static final StringA key is pointing to the warning message text in "messages.properties" file.static final StringA key is pointing to the warning message text in "messages.properties" file. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionint[]The configurable token set.int[]Returns the default token a check is interested in.int[]The tokens that this check must be registered for.private static booleanisAnonymousInnerClassEnd(int currentType, char nextChar) Check for "})" or "};" or "},".private static booleanisArrayInitialization(int currentType, int parentType) Is array initialization.private static booleanisColonOfCaseOrDefault(int parentType) Whether colon belongs to cases or defaults.private booleanisColonOfForEach(int parentType) Whether colon belongs to for-each.private booleanisEmptyBlock(DetailAST ast, int parentType) Is empty block.private static booleanisEmptyBlock(DetailAST ast, int parentType, int match) Tests if a givenDetailASTis part of an empty block.private booleanisEmptyCatch(DetailAST ast, int parentType) Tests if the givenDetailAstis part of an allowed empty catch block.private booleanTest if the givenDetailASTis part of an allowed empty constructor (ctor) block checked from RCURLY.private booleanTest if the givenDetailASTis a part of an allowed empty constructor checked from SLIST token.private booleanisEmptyLambda(DetailAST ast, int parentType) Test if the givenDetailASTis part of an allowed empty lambda block.private booleanisEmptyLoop(DetailAST ast, int parentType) Checks if loop is empty.private booleanisEmptyMethodBlock(DetailAST ast, int parentType) Test if the givenDetailASTis part of an allowed empty method block.private static booleanisEmptyType(DetailAST ast) Test if the givenDetailASTis part of an empty block.private booleanisNotRelevantSituation(DetailAST ast, int currentType) Is ast not a target of Check.private static booleanCheck if given ast is part of double brace initializer and if it should omit checking if next token is separated by whitespace.private static booleanCheck if given ast is part of double brace initializer and if it should omit checking if previous token is separated by whitespace.voidsetAllowEmptyCatches(boolean allow) Setter to allow empty catch bodies.voidsetAllowEmptyConstructors(boolean allow) Setter to allow empty constructor bodies.voidsetAllowEmptyLambdas(boolean allow) Setter to allow empty lambda bodies.voidsetAllowEmptyLoops(boolean allow) Setter to allow empty loop bodies.voidsetAllowEmptyMethods(boolean allow) Setter to allow empty method bodies.voidsetAllowEmptyTypes(boolean allow) Setter to allow empty class, interface and enum bodies.voidsetIgnoreEnhancedForColon(boolean ignore) Setter to ignore whitespace around colon in enhanced for loop.private booleanshouldCheckSeparationFromNextToken(DetailAST ast, char nextChar) Check if it should be checked if next token is separated from current by whitespace.private static booleanCheck if it should be checked if previous token is separated from current by whitespace.voidvisitToken(DetailAST ast) Called to process a token.Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
beginTree, clearViolations, destroy, finishTree, getFileContents, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokensMethods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverityMethods inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
configure, contextualize, getConfiguration, setupChild
-
Field Details
-
MSG_WS_NOT_PRECEDED
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
MSG_WS_NOT_FOLLOWED
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
allowEmptyConstructors
private boolean allowEmptyConstructorsAllow empty constructor bodies. -
allowEmptyMethods
private boolean allowEmptyMethodsAllow empty method bodies. -
allowEmptyTypes
private boolean allowEmptyTypesAllow empty class, interface and enum bodies. -
allowEmptyLoops
private boolean allowEmptyLoopsAllow empty loop bodies. -
allowEmptyLambdas
private boolean allowEmptyLambdasAllow empty lambda bodies. -
allowEmptyCatches
private boolean allowEmptyCatchesAllow empty catch bodies. -
ignoreEnhancedForColon
private boolean ignoreEnhancedForColonIgnore whitespace around colon in enhanced for loop.
-
-
Constructor Details
-
WhitespaceAroundCheck
public WhitespaceAroundCheck()
-
-
Method Details
-
getDefaultTokens
public int[] getDefaultTokens()Description copied from class:AbstractCheckReturns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.- Specified by:
getDefaultTokensin classAbstractCheck- Returns:
- the default tokens
- See Also:
-
getAcceptableTokens
public int[] getAcceptableTokens()Description copied from class:AbstractCheckThe configurable token set. Used to protect Checks against malicious users who specify an unacceptable token set in the configuration file. The default implementation returns the check's default tokens.- Specified by:
getAcceptableTokensin classAbstractCheck- Returns:
- the token set this check is designed for.
- See Also:
-
getRequiredTokens
public int[] getRequiredTokens()Description copied from class:AbstractCheckThe tokens that this check must be registered for.- Specified by:
getRequiredTokensin classAbstractCheck- Returns:
- the token set this must be registered for.
- See Also:
-
setAllowEmptyMethods
public void setAllowEmptyMethods(boolean allow) Setter to allow empty method bodies.- Parameters:
allow-trueto allow empty method bodies.
-
setAllowEmptyConstructors
public void setAllowEmptyConstructors(boolean allow) Setter to allow empty constructor bodies.- Parameters:
allow-trueto allow empty constructor bodies.
-
setIgnoreEnhancedForColon
public void setIgnoreEnhancedForColon(boolean ignore) Setter to ignore whitespace around colon in enhanced for loop.- Parameters:
ignore-trueto ignore enhanced for colon.
-
setAllowEmptyTypes
public void setAllowEmptyTypes(boolean allow) Setter to allow empty class, interface and enum bodies.- Parameters:
allow-trueto allow empty type bodies.
-
setAllowEmptyLoops
public void setAllowEmptyLoops(boolean allow) Setter to allow empty loop bodies.- Parameters:
allow-trueto allow empty loops bodies.
-
setAllowEmptyLambdas
public void setAllowEmptyLambdas(boolean allow) Setter to allow empty lambda bodies.- Parameters:
allow-trueto allow empty lambda expressions.
-
setAllowEmptyCatches
public void setAllowEmptyCatches(boolean allow) Setter to allow empty catch bodies.- Parameters:
allow-trueto allow empty catch blocks.
-
visitToken
Description copied from class:AbstractCheckCalled to process a token.- Overrides:
visitTokenin classAbstractCheck- Parameters:
ast- the token to process
-
isNotRelevantSituation
Is ast not a target of Check.- Parameters:
ast- astcurrentType- type of ast- Returns:
- true is ok to skip validation
-
shouldCheckSeparationFromPreviousToken
Check if it should be checked if previous token is separated from current by whitespace. This function is needed to recognise double brace initialization as valid, unfortunately its not possible to implement this functionality in isNotRelevantSituation method, because in this method when we return true(is not relevant) ast is later doesn't check at all. For example: new Properties() {{setProperty("double curly braces", "are not a style violation"); }}; For second left curly brace in first line when we would return true from isNotRelevantSituation it wouldn't later check that the next token(setProperty) is not separated from previous token.- Parameters:
ast- current AST.- Returns:
- true if it should be checked if previous token is separated by whitespace, false otherwise.
-
shouldCheckSeparationFromNextToken
Check if it should be checked if next token is separated from current by whitespace. Explanation why this method is needed is identical to one included in shouldCheckSeparationFromPreviousToken method.- Parameters:
ast- current AST.nextChar- next character.- Returns:
- true if it should be checked if next token is separated by whitespace, false otherwise.
-
isAnonymousInnerClassEnd
private static boolean isAnonymousInnerClassEnd(int currentType, char nextChar) Check for "})" or "};" or "},". Happens with anon-inners- Parameters:
currentType- tokennextChar- next symbol- Returns:
- true is that is end of anon inner class
-
isEmptyBlock
Is empty block.- Parameters:
ast- astparentType- parent- Returns:
- true is block is empty
-
isEmptyBlock
Tests if a givenDetailASTis part of an empty block. An example empty block might look like the followingpublic void myMethod(int val) {}In the above, the method body is an empty block ("{}").- Parameters:
ast- theDetailASTto test.parentType- the token type ofast's parent.match- the parent token type we're looking to match.- Returns:
trueifastmakes up part of an empty block contained under amatchtoken type node.
-
isColonOfCaseOrDefault
private static boolean isColonOfCaseOrDefault(int parentType) Whether colon belongs to cases or defaults.- Parameters:
parentType- parent- Returns:
- true if current token in colon of case or default tokens
-
isColonOfForEach
private boolean isColonOfForEach(int parentType) Whether colon belongs to for-each.- Parameters:
parentType- parent- Returns:
- true if current token in colon of for-each token
-
isArrayInitialization
private static boolean isArrayInitialization(int currentType, int parentType) Is array initialization.- Parameters:
currentType- current tokenparentType- parent token- Returns:
- true is current token inside array initialization
-
isEmptyMethodBlock
Test if the givenDetailASTis part of an allowed empty method block.- Parameters:
ast- theDetailASTto test.parentType- the token type ofast's parent.- Returns:
trueifastmakes up part of an allowed empty method block.
-
isEmptyCtorBlockCheckedFromRcurly
Test if the givenDetailASTis part of an allowed empty constructor (ctor) block checked from RCURLY.- Parameters:
ast- theDetailASTto test.- Returns:
trueifastmakes up part of an allowed empty constructor block.
-
isEmptyCtorBlockCheckedFromSlist
Test if the givenDetailASTis a part of an allowed empty constructor checked from SLIST token.- Parameters:
ast- theDetailASTto test.- Returns:
trueifastmakes up part of an empty constructor block.
-
isEmptyLoop
Checks if loop is empty.- Parameters:
ast- ast theDetailASTto test.parentType- the token type ofast's parent.- Returns:
trueifastmakes up part of an allowed empty loop block.
-
isEmptyLambda
Test if the givenDetailASTis part of an allowed empty lambda block.- Parameters:
ast- theDetailASTto test.parentType- the token type ofast's parent.- Returns:
trueifastmakes up part of an allowed empty lambda block.
-
isEmptyCatch
Tests if the givenDetailAstis part of an allowed empty catch block.- Parameters:
ast- theDetailAstto test.parentType- the token type ofast's parent- Returns:
trueifastmakes up part of an allowed empty catch block.
-
isEmptyType
Test if the givenDetailASTis part of an empty block. An example empty block might look like the followingclass Foo {}- Parameters:
ast- ast theDetailASTto test.- Returns:
trueifastmakes up part of an empty block contained under amatchtoken type node.
-
isPartOfDoubleBraceInitializerForPreviousToken
Check if given ast is part of double brace initializer and if it should omit checking if previous token is separated by whitespace.- Parameters:
ast- ast to check- Returns:
- true if it should omit checking for previous token, false otherwise
-
isPartOfDoubleBraceInitializerForNextToken
Check if given ast is part of double brace initializer and if it should omit checking if next token is separated by whitespace. See PR#2845 for more information why this function was needed.- Parameters:
ast- ast to check- Returns:
- true if it should omit checking for next token, false otherwise
-