Class NeedBracesCheck
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.api.AutomaticBean
-
- com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
-
- com.puppycrawl.tools.checkstyle.api.AbstractCheck
-
- com.puppycrawl.tools.checkstyle.checks.blocks.NeedBracesCheck
-
- All Implemented Interfaces:
Configurable,Contextualizable
public class NeedBracesCheck extends AbstractCheck
Checks for braces around code blocks.
-
Property
allowSingleLineStatement- allow single-line statements without braces. Type isboolean. Default value isfalse. -
Property
allowEmptyLoopBody- allow loops with empty bodies. Type isboolean. Default value isfalse. -
Property
tokens- tokens to check Type isjava.lang.String[]. Validation type istokenSet. Default value is: LITERAL_DO, LITERAL_ELSE, LITERAL_FOR, LITERAL_IF, LITERAL_WHILE.
To configure the check:
<module name="NeedBraces"/>
Example:
if (obj.isValid()) return true; // violation, single-line statements not allowed without braces if (true) { // OK return true; } else // violation, single-line statements not allowed without braces return false; for (int i = 0; i < 5; i++) { // OK ++count; } do // violation, single-line statements not allowed without braces ++count; while (false); for (int j = 0; j < 10; j++); // violation, empty loop body not allowed for(int i = 0; i < 10; value.incrementValue()); // violation, empty loop body not allowed while (counter < 10) // violation, single-line statements not allowed without braces ++count; while (value.incrementValue() < 5); // violation, empty loop body not allowed switch (num) { case 1: counter++; break; // OK }To configure the check for
ifandelseblocks:<module name="NeedBraces"> <property name="tokens" value="LITERAL_IF, LITERAL_ELSE"/> </module>
Example:
if (obj.isValid()) return true; // violation, single-line statements not allowed without braces if (true) { // OK return true; } else // violation, single-line statements not allowed without braces return false; for (int i = 0; i < 5; i++) { // OK ++count; } do // OK ++count; while (false); for (int j = 0; j < 10; j++); // OK for(int i = 0; i < 10; value.incrementValue()); // OK while (counter < 10) // OK ++count; while (value.incrementValue() < 5); // OK switch (num) { case 1: counter++; break; // OK }To configure the check to allow single-line statements (
if, while, do-while, for) without braces:<module name="NeedBraces"> <property name="allowSingleLineStatement" value="true"/> <property name="tokens" value="LITERAL_IF, LITERAL_WHILE, LITERAL_DO, LITERAL_FOR"/> </module>Example:
if (obj.isValid()) return true; // OK if (true) { // OK return true; } else // OK return false; for (int i = 0; i < 5; i++) { // OK ++count; } do // OK ++count; while (false); for (int j = 0; j < 10; j++); // violation, empty loop body not allowed for(int i = 0; i < 10; value.incrementValue()); // violation, empty loop body not allowed while (counter < 10) // OK ++count; while (value.incrementValue() < 5); // violation, empty loop body not allowed switch (num) { case 1: counter++; break; // OK } while (obj.isValid()) return true; // OK do this.notify(); while (o != null); // OK for (int i = 0; ; ) this.notify(); // OKTo configure the check to allow
case, defaultsingle-line statements without braces:<module name="NeedBraces"> <property name="tokens" value="LITERAL_CASE, LITERAL_DEFAULT"/> <property name="allowSingleLineStatement" value="true"/> </module>
Next statements won't be violated by check:
if (obj.isValid()) return true; // OK if (true) { // OK return true; } else // OK return false; for (int i = 0; i < 5; i++) { // OK ++count; } do // OK ++count; while (false); for (int j = 0; j < 10; j++); // OK for(int i = 0; i < 10; value.incrementValue()); // OK while (counter < 10) // OK ++count; while (value.incrementValue() < 5); // OK switch (num) { case 1: counter++; break; // OK case 6: counter += 10; break; // OK default: counter = 100; break; // OK }To configure the check to allow loops (
while, for) with empty bodies:<module name="NeedBraces"> <property name="allowEmptyLoopBody" value="true"/> <property name="tokens" value="LITERAL_WHILE, LITERAL_FOR"/> </module>
Example:
if (obj.isValid()) return true; // OK if (true) { // OK return true; } else // OK return false; for (int i = 0; i < 5; i++) { // OK ++count; } do // OK ++count; while (false); for (int j = 0; j < 10; j++); // OK for(int i = 0; i < 10; value.incrementValue()); // OK while (counter < 10) // violation, single-line statements not allowed without braces ++count; while (value.incrementValue() < 5); // OK switch (num) { case 1: counter++; break; // OK }To configure the check to lambdas:
<module name="NeedBraces"> <property name="tokens" value="LAMBDA"/> <property name="allowSingleLineStatement" value="true"/> </module>
Results in following:
allowedFuture.addCallback(result -> assertEquals("Invalid response", EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS), result), // violation, lambda spans 2 lines ex -> fail(ex.getMessage())); // OK allowedFuture.addCallback(result -> { return assertEquals("Invalid response", EnumSet.of(HttpMethod.GET, HttpMethod.OPTIONS), result); }, // OK ex -> fail(ex.getMessage()));Parent is
com.puppycrawl.tools.checkstyle.TreeWalkerViolation Message Keys:
-
needBraces
- Since:
- 3.0
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
AutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description private booleanallowEmptyLoopBodyAllow loops with empty bodies.private booleanallowSingleLineStatementAllow single-line statements without braces.static java.lang.StringMSG_KEY_NEED_BRACESA key is pointing to the warning message text in "messages.properties" file.
-
Constructor Summary
Constructors Constructor Description NeedBracesCheck()
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description int[]getAcceptableTokens()The configurable token set.int[]getDefaultTokens()Returns the default token a check is interested in.private static DetailASTgetLastLambdaToken(DetailAST lambda)Looks for the last token in lambda.int[]getRequiredTokens()The tokens that this check must be registered for.private static booleanhasUnbracedStatements(DetailAST ast)Checks if switch member (case, default statements) has statements without curly braces.private booleanisBracesNeeded(DetailAST ast)Checks if token needs braces.private booleanisEmptyLoopBodyAllowed(DetailAST ast)Checks if current loop has empty body and can be skipped by this check.private static booleanisInSwitchRule(DetailAST ast)Checks if current ast's parent is a switch rule, e.g.:private static booleanisSingleLineCaseGroup(DetailAST ast)Checks if switch member in case group (case or default statement) is single-line statement, e.g.:private static booleanisSingleLineDoWhile(DetailAST literalDo)Checks if current do-while statement is single-line statement, e.g.:private static booleanisSingleLineElse(DetailAST literalElse)Checks if current else statement is single-line statement, e.g.:private static booleanisSingleLineFor(DetailAST literalFor)Checks if current for statement is single-line statement, e.g.:private static booleanisSingleLineIf(DetailAST literalIf)Checks if current if statement is single-line statement, e.g.:private static booleanisSingleLineLambda(DetailAST lambda)Checks if current lambda statement is single-line statement, e.g.:private static booleanisSingleLineStatement(DetailAST statement)Checks if current statement is single-line statement, e.g.:private static booleanisSingleLineSwitchMember(DetailAST statement)Checks if switch member (case or default statement) in a switch rule or case group is on a single line.private static booleanisSingleLineSwitchRule(DetailAST ast)Checks if switch member in switch rule (case or default statement) is single-line statement, e.g.:private static booleanisSingleLineWhile(DetailAST literalWhile)Checks if current while statement is single-line statement, e.g.:private booleanisSkipStatement(DetailAST statement)Checks if current statement can be skipped by "need braces" warning.private static booleanisSwitchLabeledExpression(DetailAST ast)Checks if current expression is a switch labeled expression.voidsetAllowEmptyLoopBody(boolean allowEmptyLoopBody)Setter to allow loops with empty bodies.voidsetAllowSingleLineStatement(boolean allowSingleLineStatement)Setter to allow single-line statements without braces.private static booleanswitchRuleHasSingleExpression(DetailAST switchRule)Checks if current switch labeled expression contains only a single expression.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, setTokens
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverity
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
configure, contextualize, getConfiguration, setupChild
-
-
-
-
Field Detail
-
MSG_KEY_NEED_BRACES
public static final java.lang.String MSG_KEY_NEED_BRACES
A key is pointing to the warning message text in "messages.properties" file.- See Also:
- Constant Field Values
-
allowSingleLineStatement
private boolean allowSingleLineStatement
Allow single-line statements without braces.
-
allowEmptyLoopBody
private boolean allowEmptyLoopBody
Allow loops with empty bodies.
-
-
Constructor Detail
-
NeedBracesCheck
public NeedBracesCheck()
-
-
Method Detail
-
setAllowSingleLineStatement
public void setAllowSingleLineStatement(boolean allowSingleLineStatement)
Setter to allow single-line statements without braces.- Parameters:
allowSingleLineStatement- Check's option for skipping single-line statements
-
setAllowEmptyLoopBody
public void setAllowEmptyLoopBody(boolean allowEmptyLoopBody)
Setter to allow loops with empty bodies.- Parameters:
allowEmptyLoopBody- Check's option for allowing loops with empty body.
-
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:
TokenTypes
-
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:
TokenTypes
-
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:
TokenTypes
-
visitToken
public void visitToken(DetailAST ast)
Description copied from class:AbstractCheckCalled to process a token.- Overrides:
visitTokenin classAbstractCheck- Parameters:
ast- the token to process
-
isBracesNeeded
private boolean isBracesNeeded(DetailAST ast)
Checks if token needs braces. Some tokens have additional conditions:TokenTypes.LITERAL_FORTokenTypes.LITERAL_WHILETokenTypes.LITERAL_CASETokenTypes.LITERAL_DEFAULTTokenTypes.LITERAL_ELSETokenTypes.LAMBDA
trueis returned.- Parameters:
ast- token to check- Returns:
- result of additional checks for specific token types,
trueif there is no additional checks for token
-
isEmptyLoopBodyAllowed
private boolean isEmptyLoopBodyAllowed(DetailAST ast)
Checks if current loop has empty body and can be skipped by this check.- Parameters:
ast- for, while statements.- Returns:
- true if current loop can be skipped by check.
-
hasUnbracedStatements
private static boolean hasUnbracedStatements(DetailAST ast)
Checks if switch member (case, default statements) has statements without curly braces.- Parameters:
ast- case, default statements.- Returns:
- true if switch member has unbraced statements, false otherwise.
-
isSkipStatement
private boolean isSkipStatement(DetailAST statement)
Checks if current statement can be skipped by "need braces" warning.- Parameters:
statement- if, for, while, do-while, lambda, else, case, default statements.- Returns:
- true if current statement can be skipped by Check.
-
isSingleLineStatement
private static boolean isSingleLineStatement(DetailAST statement)
Checks if current statement is single-line statement, e.g.:if (obj.isValid()) return true;while (obj.isValid()) return true;- Parameters:
statement- if, for, while, do-while, lambda, else, case, default statements.- Returns:
- true if current statement is single-line statement.
-
isSingleLineWhile
private static boolean isSingleLineWhile(DetailAST literalWhile)
Checks if current while statement is single-line statement, e.g.:while (obj.isValid()) return true;- Parameters:
literalWhile-while statement.- Returns:
- true if current while statement is single-line statement.
-
isSingleLineDoWhile
private static boolean isSingleLineDoWhile(DetailAST literalDo)
Checks if current do-while statement is single-line statement, e.g.:do this.notify(); while (o != null);- Parameters:
literalDo-do-while statement.- Returns:
- true if current do-while statement is single-line statement.
-
isSingleLineFor
private static boolean isSingleLineFor(DetailAST literalFor)
Checks if current for statement is single-line statement, e.g.:for (int i = 0; ; ) this.notify();- Parameters:
literalFor-for statement.- Returns:
- true if current for statement is single-line statement.
-
isSingleLineIf
private static boolean isSingleLineIf(DetailAST literalIf)
Checks if current if statement is single-line statement, e.g.:if (obj.isValid()) return true;- Parameters:
literalIf-if statement.- Returns:
- true if current if statement is single-line statement.
-
isSingleLineLambda
private static boolean isSingleLineLambda(DetailAST lambda)
Checks if current lambda statement is single-line statement, e.g.:Runnable r = () -> System.out.println("Hello, world!");- Parameters:
lambda-lambda statement.- Returns:
- true if current lambda statement is single-line statement.
-
getLastLambdaToken
private static DetailAST getLastLambdaToken(DetailAST lambda)
Looks for the last token in lambda.- Parameters:
lambda- token to check.- Returns:
- last token in lambda
-
isInSwitchRule
private static boolean isInSwitchRule(DetailAST ast)
Checks if current ast's parent is a switch rule, e.g.:case 1 -> monthString = "January";- Parameters:
ast- the ast to check.- Returns:
- true if current ast belongs to a switch rule.
-
isSwitchLabeledExpression
private static boolean isSwitchLabeledExpression(DetailAST ast)
Checks if current expression is a switch labeled expression. If so, braces are not allowed e.g.:case 1 -> 4;- Parameters:
ast- the ast to check- Returns:
- true if current expression is a switch labeled expression.
-
switchRuleHasSingleExpression
private static boolean switchRuleHasSingleExpression(DetailAST switchRule)
Checks if current switch labeled expression contains only a single expression.- Parameters:
switchRule-TokenTypes.SWITCH_RULE.- Returns:
- true if current switch rule has a single expression.
-
isSingleLineSwitchMember
private static boolean isSingleLineSwitchMember(DetailAST statement)
Checks if switch member (case or default statement) in a switch rule or case group is on a single line.- Parameters:
statement-case statementordefault statement.- Returns:
- true if current switch member is single-line statement.
-
isSingleLineCaseGroup
private static boolean isSingleLineCaseGroup(DetailAST ast)
Checks if switch member in case group (case or default statement) is single-line statement, e.g.:case 1: System.out.println("case one"); break; case 2: System.out.println("case two"); break; case 3: ; default: System.out.println("default"); break;- Parameters:
ast-case statementordefault statement.- Returns:
- true if current switch member is single-line statement.
-
isSingleLineSwitchRule
private static boolean isSingleLineSwitchRule(DetailAST ast)
Checks if switch member in switch rule (case or default statement) is single-line statement, e.g.:case 1 -> System.out.println("case one"); case 2 -> System.out.println("case two"); default -> System.out.println("default");- Parameters:
ast-case statementordefault statement.- Returns:
- true if current switch label is single-line statement.
-
isSingleLineElse
private static boolean isSingleLineElse(DetailAST literalElse)
Checks if current else statement is single-line statement, e.g.:else doSomeStuff();- Parameters:
literalElse-else statement.- Returns:
- true if current else statement is single-line statement.
-
-