/
UnnecessaryParenthesesCheck.java
437 lines (407 loc) · 16.4 KB
/
UnnecessaryParenthesesCheck.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2020 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;
import com.puppycrawl.tools.checkstyle.FileStatefulCheck;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
/**
* <p>
* Checks if unnecessary parentheses are used in a statement or expression.
* The check will flag the following with warnings:
* </p>
* <pre>
* 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</pre>
* <p>
* 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. It also doesn't know
* about operator precedence and associativity; therefore it won't catch
* something like
* </p>
* <pre>
* int x = (a + b) + c;</pre>
* <p>
* In the above case, given that <em>a</em>, <em>b</em>, and <em>c</em> are
* all {@code int} variables, the parentheses around {@code a + b}
* are not needed.
* </p>
* <ul>
* <li>
* Property {@code tokens} - tokens to check
* Default value is:
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#EXPR">
* EXPR</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#IDENT">
* IDENT</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#NUM_DOUBLE">
* NUM_DOUBLE</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#NUM_FLOAT">
* NUM_FLOAT</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#NUM_INT">
* NUM_INT</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#NUM_LONG">
* NUM_LONG</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#STRING_LITERAL">
* STRING_LITERAL</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#LITERAL_NULL">
* LITERAL_NULL</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#LITERAL_FALSE">
* LITERAL_FALSE</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#LITERAL_TRUE">
* LITERAL_TRUE</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ASSIGN">
* ASSIGN</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#BAND_ASSIGN">
* BAND_ASSIGN</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#BOR_ASSIGN">
* BOR_ASSIGN</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#BSR_ASSIGN">
* BSR_ASSIGN</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#BXOR_ASSIGN">
* BXOR_ASSIGN</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#DIV_ASSIGN">
* DIV_ASSIGN</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#MINUS_ASSIGN">
* MINUS_ASSIGN</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#MOD_ASSIGN">
* MOD_ASSIGN</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#PLUS_ASSIGN">
* PLUS_ASSIGN</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#SL_ASSIGN">
* SL_ASSIGN</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#SR_ASSIGN">
* SR_ASSIGN</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#STAR_ASSIGN">
* STAR_ASSIGN</a>,
* <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#LAMBDA">
* LAMBDA</a>.
* </li>
* </ul>
* <p>
* To configure the check:
* </p>
* <pre>
* <module name="UnnecessaryParentheses"/>
* </pre>
* <p>
* Which results in the following violations:
* </p>
* <pre>
* public int square(int a, int b){
* int square = (a * b); //violation
* return (square); //violation
* }
* int sumOfSquares = 0;
* for(int i=(0); i<10; i++){ //violation
* int x = (i + 1); //violation
* sumOfSquares += (square(x * x)); //violation
* }
* double num = (10.0); //violation
* List<String> list = Arrays.asList("a1", "b1", "c1");
* myList.stream()
* .filter((s) -> s.startsWith("c")) //violation
* .forEach(System.out::println);
* </pre>
*
* @since 3.4
*/
@FileStatefulCheck
public class UnnecessaryParenthesesCheck extends AbstractCheck {
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_IDENT = "unnecessary.paren.ident";
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_ASSIGN = "unnecessary.paren.assign";
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_EXPR = "unnecessary.paren.expr";
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_LITERAL = "unnecessary.paren.literal";
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_STRING = "unnecessary.paren.string";
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_RETURN = "unnecessary.paren.return";
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_LAMBDA = "unnecessary.paren.lambda";
/** The maximum string length before we chop the string. */
private static final int MAX_QUOTED_LENGTH = 25;
/** Token types for literals. */
private static final int[] LITERALS = {
TokenTypes.NUM_DOUBLE,
TokenTypes.NUM_FLOAT,
TokenTypes.NUM_INT,
TokenTypes.NUM_LONG,
TokenTypes.STRING_LITERAL,
TokenTypes.LITERAL_NULL,
TokenTypes.LITERAL_FALSE,
TokenTypes.LITERAL_TRUE,
};
/** Token types for assignment operations. */
private static final int[] ASSIGNMENTS = {
TokenTypes.ASSIGN,
TokenTypes.BAND_ASSIGN,
TokenTypes.BOR_ASSIGN,
TokenTypes.BSR_ASSIGN,
TokenTypes.BXOR_ASSIGN,
TokenTypes.DIV_ASSIGN,
TokenTypes.MINUS_ASSIGN,
TokenTypes.MOD_ASSIGN,
TokenTypes.PLUS_ASSIGN,
TokenTypes.SL_ASSIGN,
TokenTypes.SR_ASSIGN,
TokenTypes.STAR_ASSIGN,
};
/**
* 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 DetailAST parentToSkip;
/** Depth of nested assignments. Normally this will be 0 or 1. */
private int assignDepth;
@Override
public int[] getDefaultTokens() {
return new int[] {
TokenTypes.EXPR,
TokenTypes.IDENT,
TokenTypes.NUM_DOUBLE,
TokenTypes.NUM_FLOAT,
TokenTypes.NUM_INT,
TokenTypes.NUM_LONG,
TokenTypes.STRING_LITERAL,
TokenTypes.LITERAL_NULL,
TokenTypes.LITERAL_FALSE,
TokenTypes.LITERAL_TRUE,
TokenTypes.ASSIGN,
TokenTypes.BAND_ASSIGN,
TokenTypes.BOR_ASSIGN,
TokenTypes.BSR_ASSIGN,
TokenTypes.BXOR_ASSIGN,
TokenTypes.DIV_ASSIGN,
TokenTypes.MINUS_ASSIGN,
TokenTypes.MOD_ASSIGN,
TokenTypes.PLUS_ASSIGN,
TokenTypes.SL_ASSIGN,
TokenTypes.SR_ASSIGN,
TokenTypes.STAR_ASSIGN,
TokenTypes.LAMBDA,
};
}
@Override
public int[] getAcceptableTokens() {
return new int[] {
TokenTypes.EXPR,
TokenTypes.IDENT,
TokenTypes.NUM_DOUBLE,
TokenTypes.NUM_FLOAT,
TokenTypes.NUM_INT,
TokenTypes.NUM_LONG,
TokenTypes.STRING_LITERAL,
TokenTypes.LITERAL_NULL,
TokenTypes.LITERAL_FALSE,
TokenTypes.LITERAL_TRUE,
TokenTypes.ASSIGN,
TokenTypes.BAND_ASSIGN,
TokenTypes.BOR_ASSIGN,
TokenTypes.BSR_ASSIGN,
TokenTypes.BXOR_ASSIGN,
TokenTypes.DIV_ASSIGN,
TokenTypes.MINUS_ASSIGN,
TokenTypes.MOD_ASSIGN,
TokenTypes.PLUS_ASSIGN,
TokenTypes.SL_ASSIGN,
TokenTypes.SR_ASSIGN,
TokenTypes.STAR_ASSIGN,
TokenTypes.LAMBDA,
};
}
@Override
public int[] getRequiredTokens() {
// Check can work with any of acceptable tokens
return CommonUtil.EMPTY_INT_ARRAY;
}
// -@cs[CyclomaticComplexity] All logs should be in visit token.
@Override
public void visitToken(DetailAST ast) {
final int type = ast.getType();
final DetailAST parent = ast.getParent();
if (type == TokenTypes.LAMBDA && isLambdaSingleParameterSurrounded(ast)) {
log(ast, MSG_LAMBDA, ast.getText());
}
else if (type != TokenTypes.ASSIGN
|| parent.getType() != TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR) {
final boolean surrounded = isSurrounded(ast);
// An identifier surrounded by parentheses.
if (surrounded && type == TokenTypes.IDENT) {
parentToSkip = ast.getParent();
log(ast, MSG_IDENT, ast.getText());
}
// A literal (numeric or string) surrounded by parentheses.
else if (surrounded && isInTokenList(type, LITERALS)) {
parentToSkip = ast.getParent();
if (type == TokenTypes.STRING_LITERAL) {
log(ast, MSG_STRING,
chopString(ast.getText()));
}
else {
log(ast, MSG_LITERAL, ast.getText());
}
}
// The rhs of an assignment surrounded by parentheses.
else if (isInTokenList(type, ASSIGNMENTS)) {
assignDepth++;
final DetailAST last = ast.getLastChild();
if (last.getType() == TokenTypes.RPAREN) {
log(ast, MSG_ASSIGN);
}
}
}
}
@Override
public void leaveToken(DetailAST ast) {
final int type = ast.getType();
final DetailAST parent = ast.getParent();
// shouldn't process assign in annotation pairs
if (type != TokenTypes.ASSIGN
|| parent.getType() != TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR) {
// An expression is surrounded by parentheses.
if (type == TokenTypes.EXPR) {
// If 'parentToSkip' == 'ast', then we've already logged a
// warning about an immediate child node in visitToken, so we don't
// need to log another one here.
if (parentToSkip != ast && isExprSurrounded(ast)) {
if (assignDepth >= 1) {
log(ast, MSG_ASSIGN);
}
else if (ast.getParent().getType() == TokenTypes.LITERAL_RETURN) {
log(ast, MSG_RETURN);
}
else {
log(ast, MSG_EXPR);
}
}
parentToSkip = null;
}
else if (isInTokenList(type, ASSIGNMENTS)) {
assignDepth--;
}
}
}
/**
* Tests if the given {@code DetailAST} is surrounded by parentheses.
* In short, does {@code ast} have a previous sibling whose type is
* {@code TokenTypes.LPAREN} and a next sibling whose type is {@code
* TokenTypes.RPAREN}.
* @param ast the {@code DetailAST} to check if it is surrounded by
* parentheses.
* @return {@code true} if {@code ast} is surrounded by
* parentheses.
*/
private static boolean isSurrounded(DetailAST ast) {
// if previous sibling is left parenthesis,
// next sibling can't be other than right parenthesis
final DetailAST prev = ast.getPreviousSibling();
return prev != null && prev.getType() == TokenTypes.LPAREN;
}
/**
* Tests if the given expression node is surrounded by parentheses.
* @param ast a {@code DetailAST} whose type is
* {@code TokenTypes.EXPR}.
* @return {@code true} if the expression is surrounded by
* parentheses.
*/
private static boolean isExprSurrounded(DetailAST ast) {
return ast.getFirstChild().getType() == TokenTypes.LPAREN;
}
/**
* Tests if the given lambda node has a single parameter, no defined type, and is surrounded
* by parentheses.
* @param ast a {@code DetailAST} whose type is
* {@code TokenTypes.LAMBDA}.
* @return {@code true} if the lambda has a single parameter, no defined type, and is
* surrounded by parentheses.
*/
private static boolean isLambdaSingleParameterSurrounded(DetailAST ast) {
final DetailAST firstChild = ast.getFirstChild();
boolean result = false;
if (firstChild.getType() == TokenTypes.LPAREN) {
final DetailAST parameters = firstChild.getNextSibling();
if (parameters.getChildCount(TokenTypes.PARAMETER_DEF) == 1
&& !parameters.getFirstChild().findFirstToken(TokenTypes.TYPE).hasChildren()) {
result = true;
}
}
return result;
}
/**
* Check if the given token type can be found in an array of token types.
* @param type the token type.
* @param tokens an array of token types to search.
* @return {@code true} if {@code type} was found in {@code
* tokens}.
*/
private static boolean isInTokenList(int type, int... tokens) {
// NOTE: Given the small size of the two arrays searched, I'm not sure
// it's worth bothering with doing a binary search or using a
// HashMap to do the searches.
boolean found = false;
for (int i = 0; i < tokens.length && !found; i++) {
found = tokens[i] == type;
}
return found;
}
/**
* Returns the specified string chopped to {@code MAX_QUOTED_LENGTH}
* plus an ellipsis (...) if the length of the string exceeds {@code
* MAX_QUOTED_LENGTH}.
* @param value the string to potentially chop.
* @return the chopped string if {@code string} is longer than
* {@code MAX_QUOTED_LENGTH}; otherwise {@code string}.
*/
private static String chopString(String value) {
String result = value;
if (value.length() > MAX_QUOTED_LENGTH) {
result = value.substring(0, MAX_QUOTED_LENGTH) + "...\"";
}
return result;
}
}