/
SuppressWarningsHolder.java
676 lines (626 loc) · 24.3 KB
/
SuppressWarningsHolder.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
///////////////////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
// Copyright (C) 2001-2022 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;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;
import com.puppycrawl.tools.checkstyle.StatelessCheck;
import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
import com.puppycrawl.tools.checkstyle.api.AuditEvent;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
/**
* <p>
* Maintains a set of check suppressions from {@code @SuppressWarnings} annotations.
* It allows to prevent Checkstyle from reporting violations from parts of code that were
* annotated with {@code @SuppressWarnings} and using name of the check to be excluded.
* It is possible to suppress all the checkstyle warnings with the argument {@code "all"}.
* You can also use a {@code checkstyle:} prefix to prevent compiler
* from processing these annotations.
* You can also define aliases for check names that need to be suppressed.
* </p>
* <ul>
* <li>
* Property {@code aliasList} - Specify aliases for check names that can be used in code
* within {@code SuppressWarnings}.
* Type is {@code java.lang.String[]}.
* Default value is {@code null}.
* </li>
* </ul>
* <p>
* To use default module configuration:
* </p>
* <pre>
* <module name="TreeWalker">
* <module name="MemberName"/>
* <module name="ConstantName"/>
* <module name="ParameterNumber">
* <property name="id" value="ParamNumberId"/>
* </module>
* <module name="NoWhitespaceAfter"/>
*
* <module name="SuppressWarningsHolder"/>
* </module>
* <module name="SuppressWarningsFilter"/>
* </pre>
* <pre>
* class Test {
*
* private int K; // violation
* @SuppressWarnings({"membername"})
* private int J; // violation suppressed
*
* private static final int i = 0; // violation
* @SuppressWarnings("checkstyle:constantname")
* private static final int m = 0; // violation suppressed
*
* public void needsLotsOfParameters (int a, // violation
* int b, int c, int d, int e, int f, int g, int h) {
* // ...
* }
*
* @SuppressWarnings("ParamNumberId")
* public void needsLotsOfParameters1 (int a, // violation suppressed
* int b, int c, int d, int e, int f, int g, int h) {
* // ...
* }
*
* private int [] ARR; // 2 violations
* @SuppressWarnings("all")
* private int [] ARRAY; // violations suppressed
* }
* </pre>
* <p>
* The general rule is that the argument of the {@code @SuppressWarnings} will be
* matched against class name of the check in any letter case. Adding {@code check}
* suffix is also accepted.
* </p>
* <p>
* If {@code aliasList} property was provided you can use your own names e.g. below
* code will work if there was provided a {@code ParameterNumberCheck=paramnum} in
* the {@code aliasList}:
* </p>
* <pre>
* <module name="TreeWalker">
* <module name="ParameterNumber"/>
*
* <module name="SuppressWarningsHolder">
* <property name="aliasList" value=
* "com.puppycrawl.tools.checkstyle.checks.sizes.ParameterNumberCheck=paramnum"/>
* </module>
* </module>
* <module name="SuppressWarningsFilter"/>
* </pre>
* <pre>
* class Test {
*
* public void needsLotsOfParameters (int a, // violation
* int b, int c, int d, int e, int f, int g, int h) {
* // ...
* }
*
* @SuppressWarnings("paramnum")
* public void needsLotsOfParameters1 (int a, // violation suppressed
* int b, int c, int d, int e, int f, int g, int h) {
* // ...
* }
*
* }
* </pre>
* <p>
* Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
* </p>
*
* @since 5.7
*/
@StatelessCheck
public class SuppressWarningsHolder
extends AbstractCheck {
/**
* Optional prefix for warning suppressions that are only intended to be
* recognized by checkstyle. For instance, to suppress {@code
* FallThroughCheck} only in checkstyle (and not in javac), use the
* suppression {@code "checkstyle:fallthrough"} or {@code "checkstyle:FallThrough"}.
* To suppress the warning in both tools, just use {@code "fallthrough"}.
*/
private static final String CHECKSTYLE_PREFIX = "checkstyle:";
/** Java.lang namespace prefix, which is stripped from SuppressWarnings */
private static final String JAVA_LANG_PREFIX = "java.lang.";
/** Suffix to be removed from subclasses of Check. */
private static final String CHECK_SUFFIX = "check";
/** Special warning id for matching all the warnings. */
private static final String ALL_WARNING_MATCHING_ID = "all";
/** A map from check source names to suppression aliases. */
private static final Map<String, String> CHECK_ALIAS_MAP = new HashMap<>();
/**
* A thread-local holder for the list of suppression entries for the last
* file parsed.
*/
private static final ThreadLocal<List<Entry>> ENTRIES =
ThreadLocal.withInitial(LinkedList::new);
/**
* Compiled pattern used to match whitespace in text block content.
*/
private static final Pattern WHITESPACE = Pattern.compile("\\s+");
/**
* Compiled pattern used to match preceding newline in text block content.
*/
private static final Pattern NEWLINE = Pattern.compile("\\n");
/**
* Returns the default alias for the source name of a check, which is the
* source name in lower case with any dotted prefix or "Check"/"check"
* suffix removed.
*
* @param sourceName the source name of the check (generally the class
* name)
* @return the default alias for the given check
*/
public static String getDefaultAlias(String sourceName) {
int endIndex = sourceName.length();
final String sourceNameLower = sourceName.toLowerCase(Locale.ENGLISH);
if (sourceNameLower.endsWith(CHECK_SUFFIX)) {
endIndex -= CHECK_SUFFIX.length();
}
final int startIndex = sourceNameLower.lastIndexOf('.') + 1;
return sourceNameLower.substring(startIndex, endIndex);
}
/**
* Returns the alias for the source name of a check. If an alias has been
* explicitly registered via {@link #setAliasList(String...)}, that
* alias is returned; otherwise, the default alias is used.
*
* @param sourceName the source name of the check (generally the class
* name)
* @return the current alias for the given check
*/
public static String getAlias(String sourceName) {
String checkAlias = CHECK_ALIAS_MAP.get(sourceName);
if (checkAlias == null) {
checkAlias = getDefaultAlias(sourceName);
}
return checkAlias;
}
/**
* Registers an alias for the source name of a check.
*
* @param sourceName the source name of the check (generally the class
* name)
* @param checkAlias the alias used in {@link SuppressWarnings} annotations
*/
private static void registerAlias(String sourceName, String checkAlias) {
CHECK_ALIAS_MAP.put(sourceName, checkAlias);
}
/**
* Setter to specify aliases for check names that can be used in code
* within {@code SuppressWarnings}.
*
* @param aliasList comma-separated alias assignments
* @throws IllegalArgumentException when alias item does not have '='
*/
public void setAliasList(String... aliasList) {
for (String sourceAlias : aliasList) {
final int index = sourceAlias.indexOf('=');
if (index > 0) {
registerAlias(sourceAlias.substring(0, index), sourceAlias
.substring(index + 1));
}
else if (!sourceAlias.isEmpty()) {
throw new IllegalArgumentException(
"'=' expected in alias list item: " + sourceAlias);
}
}
}
/**
* Checks for a suppression of a check with the given source name and
* location in the last file processed.
*
* @param event audit event.
* @return whether the check with the given name is suppressed at the given
* source location
*/
public static boolean isSuppressed(AuditEvent event) {
final List<Entry> entries = ENTRIES.get();
final String sourceName = event.getSourceName();
final String checkAlias = getAlias(sourceName);
final int line = event.getLine();
final int column = event.getColumn();
boolean suppressed = false;
for (Entry entry : entries) {
final boolean afterStart = isSuppressedAfterEventStart(line, column, entry);
final boolean beforeEnd = isSuppressedBeforeEventEnd(line, column, entry);
final String checkName = entry.getCheckName();
final boolean nameMatches =
ALL_WARNING_MATCHING_ID.equals(checkName)
|| checkName.equalsIgnoreCase(checkAlias)
|| getDefaultAlias(checkName).equalsIgnoreCase(checkAlias);
if (afterStart && beforeEnd
&& (nameMatches || checkName.equals(event.getModuleId()))) {
suppressed = true;
break;
}
}
return suppressed;
}
/**
* Checks whether suppression entry position is after the audit event occurrence position
* in the source file.
*
* @param line the line number in the source file where the event occurred.
* @param column the column number in the source file where the event occurred.
* @param entry suppression entry.
* @return true if suppression entry position is after the audit event occurrence position
* in the source file.
*/
private static boolean isSuppressedAfterEventStart(int line, int column, Entry entry) {
return entry.getFirstLine() < line
|| entry.getFirstLine() == line
&& (column == 0 || entry.getFirstColumn() <= column);
}
/**
* Checks whether suppression entry position is before the audit event occurrence position
* in the source file.
*
* @param line the line number in the source file where the event occurred.
* @param column the column number in the source file where the event occurred.
* @param entry suppression entry.
* @return true if suppression entry position is before the audit event occurrence position
* in the source file.
*/
private static boolean isSuppressedBeforeEventEnd(int line, int column, Entry entry) {
return entry.getLastLine() > line
|| entry.getLastLine() == line && entry
.getLastColumn() >= column;
}
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
}
@Override
public int[] getAcceptableTokens() {
return getRequiredTokens();
}
@Override
public int[] getRequiredTokens() {
return new int[] {TokenTypes.ANNOTATION};
}
@Override
public void beginTree(DetailAST rootAST) {
ENTRIES.get().clear();
}
@Override
public void visitToken(DetailAST ast) {
// check whether annotation is SuppressWarnings
// expected children: AT ( IDENT | DOT ) LPAREN <values> RPAREN
String identifier = getIdentifier(getNthChild(ast, 1));
if (identifier.startsWith(JAVA_LANG_PREFIX)) {
identifier = identifier.substring(JAVA_LANG_PREFIX.length());
}
if ("SuppressWarnings".equals(identifier)) {
getAnnotationTarget(ast).ifPresent(targetAST -> {
addSuppressions(getAllAnnotationValues(ast), targetAST);
});
}
}
/**
* Method to populate list of suppression entries.
*
* @param values
* - list of check names
* @param targetAST
* - annotation target
*/
private static void addSuppressions(List<String> values, DetailAST targetAST) {
// get text range of target
final int firstLine = targetAST.getLineNo();
final int firstColumn = targetAST.getColumnNo();
final DetailAST nextAST = targetAST.getNextSibling();
final int lastLine;
final int lastColumn;
if (nextAST == null) {
lastLine = Integer.MAX_VALUE;
lastColumn = Integer.MAX_VALUE;
}
else {
lastLine = nextAST.getLineNo();
lastColumn = nextAST.getColumnNo();
}
final List<Entry> entries = ENTRIES.get();
for (String value : values) {
// strip off the checkstyle-only prefix if present
final String checkName = removeCheckstylePrefixIfExists(value);
entries.add(new Entry(checkName, firstLine, firstColumn,
lastLine, lastColumn));
}
}
/**
* Method removes checkstyle prefix (checkstyle:) from check name if exists.
*
* @param checkName
* - name of the check
* @return check name without prefix
*/
private static String removeCheckstylePrefixIfExists(String checkName) {
String result = checkName;
if (checkName.startsWith(CHECKSTYLE_PREFIX)) {
result = checkName.substring(CHECKSTYLE_PREFIX.length());
}
return result;
}
/**
* Get all annotation values.
*
* @param ast annotation token
* @return list values
* @throws IllegalArgumentException if there is an unknown annotation value type.
*/
private static List<String> getAllAnnotationValues(DetailAST ast) {
// get values of annotation
List<String> values = Collections.emptyList();
final DetailAST lparenAST = ast.findFirstToken(TokenTypes.LPAREN);
if (lparenAST != null) {
final DetailAST nextAST = lparenAST.getNextSibling();
final int nextType = nextAST.getType();
switch (nextType) {
case TokenTypes.EXPR:
case TokenTypes.ANNOTATION_ARRAY_INIT:
values = getAnnotationValues(nextAST);
break;
case TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR:
// expected children: IDENT ASSIGN ( EXPR |
// ANNOTATION_ARRAY_INIT )
values = getAnnotationValues(getNthChild(nextAST, 2));
break;
case TokenTypes.RPAREN:
// no value present (not valid Java)
break;
default:
// unknown annotation value type (new syntax?)
throw new IllegalArgumentException("Unexpected AST: " + nextAST);
}
}
return values;
}
/**
* Get target of annotation.
*
* @param ast the AST node to get the child of
* @return get target of annotation
* @throws IllegalArgumentException if there is an unexpected container type.
*/
private static Optional<DetailAST> getAnnotationTarget(DetailAST ast) {
final Optional<DetailAST> result;
final DetailAST parentAST = ast.getParent();
switch (parentAST.getType()) {
case TokenTypes.MODIFIERS:
case TokenTypes.ANNOTATIONS:
case TokenTypes.ANNOTATION:
case TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR:
result = Optional.of(parentAST.getParent());
break;
case TokenTypes.LITERAL_DEFAULT:
result = Optional.empty();
break;
case TokenTypes.ANNOTATION_ARRAY_INIT:
result = getAnnotationTarget(parentAST);
break;
default:
// unexpected container type
throw new IllegalArgumentException("Unexpected container AST: " + parentAST);
}
return result;
}
/**
* Returns the n'th child of an AST node.
*
* @param ast the AST node to get the child of
* @param index the index of the child to get
* @return the n'th child of the given AST node, or {@code null} if none
*/
private static DetailAST getNthChild(DetailAST ast, int index) {
DetailAST child = ast.getFirstChild();
for (int i = 0; i < index && child != null; ++i) {
child = child.getNextSibling();
}
return child;
}
/**
* Returns the Java identifier represented by an AST.
*
* @param ast an AST node for an IDENT or DOT
* @return the Java identifier represented by the given AST subtree
* @throws IllegalArgumentException if the AST is invalid
*/
private static String getIdentifier(DetailAST ast) {
if (ast == null) {
throw new IllegalArgumentException("Identifier AST expected, but get null.");
}
final String identifier;
if (ast.getType() == TokenTypes.IDENT) {
identifier = ast.getText();
}
else {
identifier = getIdentifier(ast.getFirstChild()) + "."
+ getIdentifier(ast.getLastChild());
}
return identifier;
}
/**
* Returns the literal string expression represented by an AST.
*
* @param ast an AST node for an EXPR
* @return the Java string represented by the given AST expression
* or empty string if expression is too complex
* @throws IllegalArgumentException if the AST is invalid
*/
private static String getStringExpr(DetailAST ast) {
final DetailAST firstChild = ast.getFirstChild();
String expr = "";
switch (firstChild.getType()) {
case TokenTypes.STRING_LITERAL:
// NOTE: escaped characters are not unescaped
final String quotedText = firstChild.getText();
expr = quotedText.substring(1, quotedText.length() - 1);
break;
case TokenTypes.IDENT:
expr = firstChild.getText();
break;
case TokenTypes.DOT:
expr = firstChild.getLastChild().getText();
break;
case TokenTypes.TEXT_BLOCK_LITERAL_BEGIN:
final String textBlockContent = firstChild.getFirstChild().getText();
expr = getContentWithoutPrecedingWhitespace(textBlockContent);
break;
default:
// annotations with complex expressions cannot suppress warnings
}
return expr;
}
/**
* Returns the annotation values represented by an AST.
*
* @param ast an AST node for an EXPR or ANNOTATION_ARRAY_INIT
* @return the list of Java string represented by the given AST for an
* expression or annotation array initializer
* @throws IllegalArgumentException if the AST is invalid
*/
private static List<String> getAnnotationValues(DetailAST ast) {
final List<String> annotationValues;
switch (ast.getType()) {
case TokenTypes.EXPR:
annotationValues = Collections.singletonList(getStringExpr(ast));
break;
case TokenTypes.ANNOTATION_ARRAY_INIT:
annotationValues = findAllExpressionsInChildren(ast);
break;
default:
throw new IllegalArgumentException(
"Expression or annotation array initializer AST expected: " + ast);
}
return annotationValues;
}
/**
* Method looks at children and returns list of expressions in strings.
*
* @param parent ast, that contains children
* @return list of expressions in strings
*/
private static List<String> findAllExpressionsInChildren(DetailAST parent) {
final List<String> valueList = new LinkedList<>();
DetailAST childAST = parent.getFirstChild();
while (childAST != null) {
if (childAST.getType() == TokenTypes.EXPR) {
valueList.add(getStringExpr(childAST));
}
childAST = childAST.getNextSibling();
}
return valueList;
}
/**
* Remove preceding newline and whitespace from the content of a text block.
*
* @param textBlockContent the actual text in a text block.
* @return content of text block with preceding whitespace and newline removed.
*/
private static String getContentWithoutPrecedingWhitespace(String textBlockContent) {
final String contentWithNoPrecedingNewline =
NEWLINE.matcher(textBlockContent).replaceAll("");
return WHITESPACE.matcher(contentWithNoPrecedingNewline).replaceAll("");
}
@Override
public void destroy() {
super.destroy();
ENTRIES.remove();
}
/** Records a particular suppression for a region of a file. */
private static class Entry {
/** The source name of the suppressed check. */
private final String checkName;
/** The suppression region for the check - first line. */
private final int firstLine;
/** The suppression region for the check - first column. */
private final int firstColumn;
/** The suppression region for the check - last line. */
private final int lastLine;
/** The suppression region for the check - last column. */
private final int lastColumn;
/**
* Constructs a new suppression region entry.
*
* @param checkName the source name of the suppressed check
* @param firstLine the first line of the suppression region
* @param firstColumn the first column of the suppression region
* @param lastLine the last line of the suppression region
* @param lastColumn the last column of the suppression region
*/
/* package */ Entry(String checkName, int firstLine, int firstColumn,
int lastLine, int lastColumn) {
this.checkName = checkName;
this.firstLine = firstLine;
this.firstColumn = firstColumn;
this.lastLine = lastLine;
this.lastColumn = lastColumn;
}
/**
* Gets the source name of the suppressed check.
*
* @return the source name of the suppressed check
*/
public String getCheckName() {
return checkName;
}
/**
* Gets the first line of the suppression region.
*
* @return the first line of the suppression region
*/
public int getFirstLine() {
return firstLine;
}
/**
* Gets the first column of the suppression region.
*
* @return the first column of the suppression region
*/
public int getFirstColumn() {
return firstColumn;
}
/**
* Gets the last line of the suppression region.
*
* @return the last line of the suppression region
*/
public int getLastLine() {
return lastLine;
}
/**
* Gets the last column of the suppression region.
*
* @return the last column of the suppression region
*/
public int getLastColumn() {
return lastColumn;
}
}
}