View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2024 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.annotation;
21  
22  import java.util.Objects;
23  import java.util.regex.Matcher;
24  import java.util.regex.Pattern;
25  
26  import com.puppycrawl.tools.checkstyle.StatelessCheck;
27  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
28  import com.puppycrawl.tools.checkstyle.api.DetailAST;
29  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
30  import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil;
31  import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
32  
33  /**
34   * <p>
35   * Allows to specify what warnings that
36   * {@code @SuppressWarnings} is not allowed to suppress.
37   * You can also specify a list of TokenTypes that
38   * the configured warning(s) cannot be suppressed on.
39   * </p>
40   * <p>
41   * Limitations:  This check does not consider conditionals
42   * inside the &#64;SuppressWarnings annotation.
43   * </p>
44   * <p>
45   * For example:
46   * {@code @SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused")}.
47   * According to the above example, the "unused" warning is being suppressed
48   * not the "unchecked" or "foo" warnings.  All of these warnings will be
49   * considered and matched against regardless of what the conditional
50   * evaluates to.
51   * The check also does not support code like {@code @SuppressWarnings("un" + "used")},
52   * {@code @SuppressWarnings((String) "unused")} or
53   * {@code @SuppressWarnings({('u' + (char)'n') + (""+("used" + (String)"")),})}.
54   * </p>
55   * <p>
56   * By default, any warning specified will be disallowed on
57   * all legal TokenTypes unless otherwise specified via
58   * the tokens property.
59   * </p>
60   * <p>
61   * Also, by default warnings that are empty strings or all
62   * whitespace (regex: ^$|^\s+$) are flagged.  By specifying,
63   * the format property these defaults no longer apply.
64   * </p>
65   * <p>This check can be configured so that the "unchecked"
66   * and "unused" warnings cannot be suppressed on
67   * anything but variable and parameter declarations.
68   * See below of an example.
69   * </p>
70   * <ul>
71   * <li>
72   * Property {@code format} - Specify the RegExp to match against warnings. Any warning
73   * being suppressed matching this pattern will be flagged.
74   * Type is {@code java.util.regex.Pattern}.
75   * Default value is {@code "^\s*+$"}.
76   * </li>
77   * <li>
78   * Property {@code tokens} - tokens to check
79   * Type is {@code java.lang.String[]}.
80   * Validation type is {@code tokenSet}.
81   * Default value is:
82   * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#CLASS_DEF">
83   * CLASS_DEF</a>,
84   * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#INTERFACE_DEF">
85   * INTERFACE_DEF</a>,
86   * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ENUM_DEF">
87   * ENUM_DEF</a>,
88   * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ANNOTATION_DEF">
89   * ANNOTATION_DEF</a>,
90   * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ANNOTATION_FIELD_DEF">
91   * ANNOTATION_FIELD_DEF</a>,
92   * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ENUM_CONSTANT_DEF">
93   * ENUM_CONSTANT_DEF</a>,
94   * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#PARAMETER_DEF">
95   * PARAMETER_DEF</a>,
96   * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#VARIABLE_DEF">
97   * VARIABLE_DEF</a>,
98   * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#METHOD_DEF">
99   * METHOD_DEF</a>,
100  * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#CTOR_DEF">
101  * CTOR_DEF</a>,
102  * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#COMPACT_CTOR_DEF">
103  * COMPACT_CTOR_DEF</a>,
104  * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#RECORD_DEF">
105  * RECORD_DEF</a>.
106  * </li>
107  * </ul>
108  * <p>
109  * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
110  * </p>
111  * <p>
112  * Violation Message Keys:
113  * </p>
114  * <ul>
115  * <li>
116  * {@code suppressed.warning.not.allowed}
117  * </li>
118  * </ul>
119  *
120  * @since 5.0
121  */
122 @StatelessCheck
123 public class SuppressWarningsCheck extends AbstractCheck {
124 
125     /**
126      * A key is pointing to the warning message text in "messages.properties"
127      * file.
128      */
129     public static final String MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED =
130         "suppressed.warning.not.allowed";
131 
132     /** {@link SuppressWarnings SuppressWarnings} annotation name. */
133     private static final String SUPPRESS_WARNINGS = "SuppressWarnings";
134 
135     /**
136      * Fully-qualified {@link SuppressWarnings SuppressWarnings}
137      * annotation name.
138      */
139     private static final String FQ_SUPPRESS_WARNINGS =
140         "java.lang." + SUPPRESS_WARNINGS;
141 
142     /**
143      * Specify the RegExp to match against warnings. Any warning
144      * being suppressed matching this pattern will be flagged.
145      */
146     private Pattern format = Pattern.compile("^\\s*+$");
147 
148     /**
149      * Setter to specify the RegExp to match against warnings. Any warning
150      * being suppressed matching this pattern will be flagged.
151      *
152      * @param pattern the new pattern
153      * @since 5.0
154      */
155     public final void setFormat(Pattern pattern) {
156         format = pattern;
157     }
158 
159     @Override
160     public final int[] getDefaultTokens() {
161         return getAcceptableTokens();
162     }
163 
164     @Override
165     public final int[] getAcceptableTokens() {
166         return new int[] {
167             TokenTypes.CLASS_DEF,
168             TokenTypes.INTERFACE_DEF,
169             TokenTypes.ENUM_DEF,
170             TokenTypes.ANNOTATION_DEF,
171             TokenTypes.ANNOTATION_FIELD_DEF,
172             TokenTypes.ENUM_CONSTANT_DEF,
173             TokenTypes.PARAMETER_DEF,
174             TokenTypes.VARIABLE_DEF,
175             TokenTypes.METHOD_DEF,
176             TokenTypes.CTOR_DEF,
177             TokenTypes.COMPACT_CTOR_DEF,
178             TokenTypes.RECORD_DEF,
179         };
180     }
181 
182     @Override
183     public int[] getRequiredTokens() {
184         return CommonUtil.EMPTY_INT_ARRAY;
185     }
186 
187     @Override
188     public void visitToken(final DetailAST ast) {
189         final DetailAST annotation = getSuppressWarnings(ast);
190 
191         if (annotation != null) {
192             final DetailAST warningHolder =
193                 findWarningsHolder(annotation);
194 
195             final DetailAST token =
196                     warningHolder.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR);
197 
198             // case like '@SuppressWarnings(value = UNUSED)'
199             final DetailAST parent = Objects.requireNonNullElse(token, warningHolder);
200             DetailAST warning = parent.findFirstToken(TokenTypes.EXPR);
201 
202             // rare case with empty array ex: @SuppressWarnings({})
203             if (warning == null) {
204                 // check to see if empty warnings are forbidden -- are by default
205                 logMatch(warningHolder, "");
206             }
207             else {
208                 while (warning != null) {
209                     if (warning.getType() == TokenTypes.EXPR) {
210                         final DetailAST fChild = warning.getFirstChild();
211                         switch (fChild.getType()) {
212                             // typical case
213                             case TokenTypes.STRING_LITERAL:
214                                 final String warningText =
215                                     removeQuotes(warning.getFirstChild().getText());
216                                 logMatch(warning, warningText);
217                                 break;
218                             // conditional case
219                             // ex:
220                             // @SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused")
221                             case TokenTypes.QUESTION:
222                                 walkConditional(fChild);
223                                 break;
224                             default:
225                                 // Known limitation: cases like @SuppressWarnings("un" + "used") or
226                                 // @SuppressWarnings((String) "unused") are not properly supported,
227                                 // but they should not cause exceptions.
228                                 // Also constant as param
229                                 // ex: public static final String UNCHECKED = "unchecked";
230                                 // @SuppressWarnings(UNCHECKED)
231                                 // or
232                                 // @SuppressWarnings(SomeClass.UNCHECKED)
233                         }
234                     }
235                     warning = warning.getNextSibling();
236                 }
237             }
238         }
239     }
240 
241     /**
242      * Gets the {@link SuppressWarnings SuppressWarnings} annotation
243      * that is annotating the AST.  If the annotation does not exist
244      * this method will return {@code null}.
245      *
246      * @param ast the AST
247      * @return the {@link SuppressWarnings SuppressWarnings} annotation
248      */
249     private static DetailAST getSuppressWarnings(DetailAST ast) {
250         DetailAST annotation = AnnotationUtil.getAnnotation(ast, SUPPRESS_WARNINGS);
251 
252         if (annotation == null) {
253             annotation = AnnotationUtil.getAnnotation(ast, FQ_SUPPRESS_WARNINGS);
254         }
255         return annotation;
256     }
257 
258     /**
259      * This method looks for a warning that matches a configured expression.
260      * If found it logs a violation at the given AST.
261      *
262      * @param ast the location to place the violation
263      * @param warningText the warning.
264      */
265     private void logMatch(DetailAST ast, final String warningText) {
266         final Matcher matcher = format.matcher(warningText);
267         if (matcher.matches()) {
268             log(ast,
269                     MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, warningText);
270         }
271     }
272 
273     /**
274      * Find the parent (holder) of the of the warnings (Expr).
275      *
276      * @param annotation the annotation
277      * @return a Token representing the expr.
278      */
279     private static DetailAST findWarningsHolder(final DetailAST annotation) {
280         final DetailAST annValuePair =
281             annotation.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR);
282 
283         final DetailAST annArrayInitParent = Objects.requireNonNullElse(annValuePair, annotation);
284         final DetailAST annArrayInit = annArrayInitParent
285                 .findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT);
286         return Objects.requireNonNullElse(annArrayInit, annotation);
287     }
288 
289     /**
290      * Strips a single double quote from the front and back of a string.
291      *
292      * <p>For example:</p>
293      * <pre>
294      * Input String = "unchecked"
295      * </pre>
296      * Output String = unchecked
297      *
298      * @param warning the warning string
299      * @return the string without two quotes
300      */
301     private static String removeQuotes(final String warning) {
302         return warning.substring(1, warning.length() - 1);
303     }
304 
305     /**
306      * Recursively walks a conditional expression checking the left
307      * and right sides, checking for matches and
308      * logging violations.
309      *
310      * @param cond a Conditional type
311      *     {@link TokenTypes#QUESTION QUESTION}
312      * @noinspection TailRecursion
313      * @noinspectionreason TailRecursion - until issue #14814
314      */
315     private void walkConditional(final DetailAST cond) {
316         if (cond.getType() == TokenTypes.QUESTION) {
317             walkConditional(getCondLeft(cond));
318             walkConditional(getCondRight(cond));
319         }
320         else {
321             final String warningText =
322                     removeQuotes(cond.getText());
323             logMatch(cond, warningText);
324         }
325     }
326 
327     /**
328      * Retrieves the left side of a conditional.
329      *
330      * @param cond cond a conditional type
331      *     {@link TokenTypes#QUESTION QUESTION}
332      * @return either the value
333      *     or another conditional
334      */
335     private static DetailAST getCondLeft(final DetailAST cond) {
336         final DetailAST colon = cond.findFirstToken(TokenTypes.COLON);
337         return colon.getPreviousSibling();
338     }
339 
340     /**
341      * Retrieves the right side of a conditional.
342      *
343      * @param cond a conditional type
344      *     {@link TokenTypes#QUESTION QUESTION}
345      * @return either the value
346      *     or another conditional
347      */
348     private static DetailAST getCondRight(final DetailAST cond) {
349         final DetailAST colon = cond.findFirstToken(TokenTypes.COLON);
350         return colon.getNextSibling();
351     }
352 
353 }