Class UnnecessaryParenthesesCheck
- All Implemented Interfaces:
Configurable
,Contextualizable
return (x); // parens around identifier return (x + 1); // parens around return value int x = (y / 2 + 1); // parens around assignment rhs for (int i = (0); i < 10; i++) { // parens around literal t -= (z + 1); // parens around assignment rhs boolean a = (x > 7 && y > 5) // parens around expression || z < 9; boolean b = (~a) > -27 // parens around ~a && (a-- < 30); // parens around expression
The check is not "type aware", that is to say, it can't tell if parentheses are unnecessary based on the types in an expression. The check is partially aware about operator precedence but unaware about operator associativity. It won't catch cases such as:
int x = (a + b) + c; // 1st Case boolean p = true; // 2nd Case int q = 4; int r = 3; if (p == (q <= r)) {}
In the first case, given that a, b, and c are
all int
variables, the parentheses around a + b
are not needed.
In the second case, parentheses are required as q, r are
of type int
and p is of type boolean
and removing parentheses will give a compile-time error. Even if q
and r were boolean
still there will be no violation
raised as check is not "type aware".
The partial support for operator precedence includes cases of the following type:
boolean a = true, b = true; boolean c = false, d = false; if ((a && b) || c) { // violation, unnecessary paren } if (a && (b || c)) { // ok } if ((a == b) && c) { // violation, unnecessary paren } String e = "e"; if ((e instanceof String) && a || b) { // violation, unnecessary paren } int f = 0; int g = 0; if (!(f >= g) // ok && (g > f)) { // violation, unnecessary paren } if ((++f) > g && a) { // violation, unnecessary paren }
-
Property
tokens
- tokens to check Type isjava.lang.String[]
. Validation type istokenSet
. Default value is: EXPR, IDENT, NUM_DOUBLE, NUM_FLOAT, NUM_INT, NUM_LONG, STRING_LITERAL, LITERAL_NULL, LITERAL_FALSE, LITERAL_TRUE, ASSIGN, BAND_ASSIGN, BOR_ASSIGN, BSR_ASSIGN, BXOR_ASSIGN, DIV_ASSIGN, MINUS_ASSIGN, MOD_ASSIGN, PLUS_ASSIGN, SL_ASSIGN, SR_ASSIGN, STAR_ASSIGN, LAMBDA, TEXT_BLOCK_LITERAL_BEGIN, LAND, LOR, LITERAL_INSTANCEOF, GT, LT, GE, LE, EQUAL, NOT_EQUAL, UNARY_MINUS, UNARY_PLUS, INC, DEC, LNOT, BNOT, POST_INC, POST_DEC.
Parent is com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
-
unnecessary.paren.assign
-
unnecessary.paren.expr
-
unnecessary.paren.ident
-
unnecessary.paren.lambda
-
unnecessary.paren.literal
-
unnecessary.paren.return
-
unnecessary.paren.string
- Since:
- 3.4
-
Nested Class Summary
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions
-
Field Summary
FieldsModifier and TypeFieldDescriptionprivate int
Depth of nested assignments.private static final int[]
Token types for assignment operations.private static final int[]
Token types for bitwise binary operator.private static final int[]
Token types for conditional operators.private static final int[]
Token types for literals.private static final int
The maximum string length before we chop the string.static final String
A key is pointing to the warning message text in "messages.properties" file.static final String
A key is pointing to the warning message text in "messages.properties" file.static final String
A key is pointing to the warning message text in "messages.properties" file.static final String
A key is pointing to the warning message text in "messages.properties" file.static final String
A key is pointing to the warning message text in "messages.properties" file.static final String
A key is pointing to the warning message text in "messages.properties" file.static final String
A key is pointing to the warning message text in "messages.properties" file.private static final Pattern
Compiled pattern used to match newline control characters, for replacement.private DetailAST
Used to test if logging a warning in a parent node may be skipped because a warning was already logged on an immediate child node.private static final String
String used to amend TEXT_BLOCK_CONTENT so that it matches STRING_LITERAL.private static final int[]
Token types for relation operator.private static final int[]
Token types for unary and postfix operators. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprivate static boolean
Check if bitwise binary operator has unnecessary parentheses.private static boolean
Check if conditional or relational operator has unnecessary parentheses.private void
checkExpression
(DetailAST ast) Checks whether an expression is surrounded by parentheses.private static String
chopString
(String value) Returns the specified string chopped toMAX_QUOTED_LENGTH
plus an ellipsis (...) if the length of the string exceedsMAX_QUOTED_LENGTH
.int[]
The configurable token set.int[]
Returns the default token a check is interested in.getParenthesesChildrenAroundQuestion
(DetailAST questionToken) Returns the direct LPAREN tokens children to a given QUESTION token which contain an expression not a literal variable.int[]
The tokens that this check must be registered for.private static boolean
Check if token type is bitwise binary or conditional or relational operator.private static boolean
Tests if the given expression node is surrounded by parentheses.private static boolean
Tests if the given node has a single parameter, no defined type, and is surrounded by parentheses.private static boolean
isSurrounded
(DetailAST ast) Tests if the givenDetailAST
is surrounded by parentheses.void
leaveToken
(DetailAST ast) Called after all the child nodes have been process.private static boolean
Checks if conditional, relational, bitwise binary operator, unary and postfix operators in expressions are surrounded by unnecessary parentheses.void
visitToken
(DetailAST ast) Called to process a token.Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
beginTree, clearViolations, destroy, finishTree, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, isCommentNodesRequired, 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.AbstractAutomaticBean
configure, contextualize, getConfiguration, setupChild
-
Field Details
-
MSG_IDENT
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
MSG_ASSIGN
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
MSG_EXPR
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
MSG_LITERAL
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
MSG_STRING
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
MSG_RETURN
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
MSG_LAMBDA
A key is pointing to the warning message text in "messages.properties" file.- See Also:
-
NEWLINE
Compiled pattern used to match newline control characters, for replacement. -
QUOTE
String used to amend TEXT_BLOCK_CONTENT so that it matches STRING_LITERAL.- See Also:
-
MAX_QUOTED_LENGTH
The maximum string length before we chop the string.- See Also:
-
LITERALS
Token types for literals. -
ASSIGNMENTS
Token types for assignment operations. -
CONDITIONAL_OPERATOR
Token types for conditional operators. -
RELATIONAL_OPERATOR
Token types for relation operator. -
UNARY_AND_POSTFIX
Token types for unary and postfix operators. -
BITWISE_BINARY_OPERATORS
Token types for bitwise binary operator. -
parentToSkip
Used to test if logging a warning in a parent node may be skipped because a warning was already logged on an immediate child node. -
assignDepth
Depth of nested assignments. Normally this will be 0 or 1.
-
-
Constructor Details
-
UnnecessaryParenthesesCheck
public UnnecessaryParenthesesCheck()
-
-
Method Details
-
getDefaultTokens
Description copied from class:AbstractCheck
Returns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.- Specified by:
getDefaultTokens
in classAbstractCheck
- Returns:
- the default tokens
- See Also:
-
getAcceptableTokens
Description copied from class:AbstractCheck
The 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:
getAcceptableTokens
in classAbstractCheck
- Returns:
- the token set this check is designed for.
- See Also:
-
getRequiredTokens
Description copied from class:AbstractCheck
The tokens that this check must be registered for.- Specified by:
getRequiredTokens
in classAbstractCheck
- Returns:
- the token set this must be registered for.
- See Also:
-
visitToken
Description copied from class:AbstractCheck
Called to process a token.- Overrides:
visitToken
in classAbstractCheck
- Parameters:
ast
- the token to process
-
leaveToken
Description copied from class:AbstractCheck
Called after all the child nodes have been process.- Overrides:
leaveToken
in classAbstractCheck
- Parameters:
ast
- the token leaving
-
isSurrounded
Tests if the givenDetailAST
is surrounded by parentheses.- Parameters:
ast
- theDetailAST
to check if it is surrounded by parentheses.- Returns:
true
ifast
is surrounded by parentheses.
-
isExprSurrounded
Tests if the given expression node is surrounded by parentheses.- Parameters:
ast
- aDetailAST
whose type isTokenTypes.EXPR
.- Returns:
true
if the expression is surrounded by parentheses.
-
checkExpression
Checks whether an expression is surrounded by parentheses.- Parameters:
ast
- theDetailAST
to check if it is surrounded by parentheses.
-
unnecessaryParenAroundOperators
Checks if conditional, relational, bitwise binary operator, unary and postfix operators in expressions are surrounded by unnecessary parentheses.- Parameters:
ast
- theDetailAST
to check if it is surrounded by unnecessary parentheses.- Returns:
true
if the expression is surrounded by unnecessary parentheses.
-
checkConditionalOrRelationalOperator
Check if conditional or relational operator has unnecessary parentheses.- Parameters:
ast
- to check if surrounded by unnecessary parentheses- Returns:
- true if unnecessary parenthesis
-
checkBitwiseBinaryOperator
Check if bitwise binary operator has unnecessary parentheses.- Parameters:
ast
- to check if surrounded by unnecessary parentheses- Returns:
- true if unnecessary parenthesis
-
isBitWiseBinaryOrConditionalOrRelationalOperator
Check if token type is bitwise binary or conditional or relational operator.- Parameters:
type
- Token type to check- Returns:
- true if it is bitwise binary or conditional operator
-
isLambdaSingleParameterSurrounded
Tests if the given node has a single parameter, no defined type, and is surrounded by parentheses. This condition can only be true for lambdas.- Parameters:
ast
- aDetailAST
node- Returns:
true
if the lambda has a single parameter, no defined type, and is surrounded by parentheses.
-
getParenthesesChildrenAroundQuestion
Returns the direct LPAREN tokens children to a given QUESTION token which contain an expression not a literal variable.- Parameters:
questionToken
-DetailAST
question token to be checked- Returns:
- the direct children to the given question token which their types are LPAREN tokens and not contain a literal inside the parentheses
-
chopString
Returns the specified string chopped toMAX_QUOTED_LENGTH
plus an ellipsis (...) if the length of the string exceedsMAX_QUOTED_LENGTH
.- Parameters:
value
- the string to potentially chop.- Returns:
- the chopped string if
string
is longer thanMAX_QUOTED_LENGTH
; otherwisestring
.
-