001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.checks.annotation;
021
022import java.util.regex.Matcher;
023import java.util.regex.Pattern;
024
025import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
026import com.puppycrawl.tools.checkstyle.api.DetailAST;
027import com.puppycrawl.tools.checkstyle.api.TokenTypes;
028import com.puppycrawl.tools.checkstyle.utils.AnnotationUtility;
029import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
030
031/**
032 * <p>
033 * This check allows you to specify what warnings that
034 * {@link SuppressWarnings SuppressWarnings} is not
035 * allowed to suppress.  You can also specify a list
036 * of TokenTypes that the configured warning(s) cannot
037 * be suppressed on.
038 * </p>
039 *
040 * <p>
041 * The {@link #setFormat warnings} property is a
042 * regex pattern.  Any warning being suppressed matching
043 * this pattern will be flagged.
044 * </p>
045 *
046 * <p>
047 * By default, any warning specified will be disallowed on
048 * all legal TokenTypes unless otherwise specified via
049 * the
050 * {@link AbstractCheck#setTokens(String[]) tokens}
051 * property.
052 *
053 * Also, by default warnings that are empty strings or all
054 * whitespace (regex: ^$|^\s+$) are flagged.  By specifying,
055 * the format property these defaults no longer apply.
056 * </p>
057 *
058 * <p>Limitations:  This check does not consider conditionals
059 * inside the SuppressWarnings annotation. <br>
060 * For example:
061 * {@code @SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused")}.
062 * According to the above example, the "unused" warning is being suppressed
063 * not the "unchecked" or "foo" warnings.  All of these warnings will be
064 * considered and matched against regardless of what the conditional
065 * evaluates to.
066 * <br>
067 * The check also does not support code like {@code @SuppressWarnings("un" + "used")},
068 * {@code @SuppressWarnings((String) "unused")} or
069 * {@code @SuppressWarnings({('u' + (char)'n') + (""+("used" + (String)"")),})}.
070 * </p>
071 *
072 * <p>This check can be configured so that the "unchecked"
073 * and "unused" warnings cannot be suppressed on
074 * anything but variable and parameter declarations.
075 * See below of an example.
076 * </p>
077 *
078 * <pre>
079 * &lt;module name=&quot;SuppressWarnings&quot;&gt;
080 *    &lt;property name=&quot;format&quot;
081 *        value=&quot;^unchecked$|^unused$&quot;/&gt;
082 *    &lt;property name=&quot;tokens&quot;
083 *        value=&quot;
084 *        CLASS_DEF,INTERFACE_DEF,ENUM_DEF,
085 *        ANNOTATION_DEF,ANNOTATION_FIELD_DEF,
086 *        ENUM_CONSTANT_DEF,METHOD_DEF,CTOR_DEF
087 *        &quot;/&gt;
088 * &lt;/module&gt;
089 * </pre>
090 * @author Travis Schneeberger
091 */
092public class SuppressWarningsCheck extends AbstractCheck {
093    /**
094     * A key is pointing to the warning message text in "messages.properties"
095     * file.
096     */
097    public static final String MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED =
098        "suppressed.warning.not.allowed";
099
100    /** {@link SuppressWarnings SuppressWarnings} annotation name. */
101    private static final String SUPPRESS_WARNINGS = "SuppressWarnings";
102
103    /**
104     * Fully-qualified {@link SuppressWarnings SuppressWarnings}
105     * annotation name.
106     */
107    private static final String FQ_SUPPRESS_WARNINGS =
108        "java.lang." + SUPPRESS_WARNINGS;
109
110    /** The regexp to match against. */
111    private Pattern format = Pattern.compile("^$|^\\s+$");
112
113    /**
114     * Set the format for the specified regular expression.
115     * @param pattern the new pattern
116     */
117    public final void setFormat(Pattern pattern) {
118        format = pattern;
119    }
120
121    @Override
122    public final int[] getDefaultTokens() {
123        return getAcceptableTokens();
124    }
125
126    @Override
127    public final int[] getAcceptableTokens() {
128        return new int[] {
129            TokenTypes.CLASS_DEF,
130            TokenTypes.INTERFACE_DEF,
131            TokenTypes.ENUM_DEF,
132            TokenTypes.ANNOTATION_DEF,
133            TokenTypes.ANNOTATION_FIELD_DEF,
134            TokenTypes.ENUM_CONSTANT_DEF,
135            TokenTypes.PARAMETER_DEF,
136            TokenTypes.VARIABLE_DEF,
137            TokenTypes.METHOD_DEF,
138            TokenTypes.CTOR_DEF,
139        };
140    }
141
142    @Override
143    public int[] getRequiredTokens() {
144        return CommonUtils.EMPTY_INT_ARRAY;
145    }
146
147    @Override
148    public void visitToken(final DetailAST ast) {
149        final DetailAST annotation = getSuppressWarnings(ast);
150
151        if (annotation != null) {
152            final DetailAST warningHolder =
153                findWarningsHolder(annotation);
154
155            final DetailAST token =
156                    warningHolder.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR);
157            DetailAST warning;
158
159            if (token == null) {
160                warning = warningHolder.findFirstToken(TokenTypes.EXPR);
161            }
162            else {
163                // case like '@SuppressWarnings(value = UNUSED)'
164                warning = token.findFirstToken(TokenTypes.EXPR);
165            }
166
167            //rare case with empty array ex: @SuppressWarnings({})
168            if (warning == null) {
169                //check to see if empty warnings are forbidden -- are by default
170                logMatch(warningHolder.getLineNo(),
171                    warningHolder.getColumnNo(), "");
172            }
173            else {
174                while (warning != null) {
175                    if (warning.getType() == TokenTypes.EXPR) {
176                        final DetailAST fChild = warning.getFirstChild();
177                        switch (fChild.getType()) {
178                            //typical case
179                            case TokenTypes.STRING_LITERAL:
180                                final String warningText =
181                                    removeQuotes(warning.getFirstChild().getText());
182                                logMatch(warning.getLineNo(),
183                                        warning.getColumnNo(), warningText);
184                                break;
185                            // conditional case
186                            // ex:
187                            // @SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused")
188                            case TokenTypes.QUESTION:
189                                walkConditional(fChild);
190                                break;
191                            // param in constant case
192                            // ex: public static final String UNCHECKED = "unchecked";
193                            // @SuppressWarnings(UNCHECKED)
194                            // or
195                            // @SuppressWarnings(SomeClass.UNCHECKED)
196                            case TokenTypes.IDENT:
197                            case TokenTypes.DOT:
198                                break;
199                            default:
200                                // Known limitation: cases like @SuppressWarnings("un" + "used") or
201                                // @SuppressWarnings((String) "unused") are not properly supported,
202                                // but they should not cause exceptions.
203                        }
204                    }
205                    warning = warning.getNextSibling();
206                }
207            }
208        }
209    }
210
211    /**
212     * Gets the {@link SuppressWarnings SuppressWarnings} annotation
213     * that is annotating the AST.  If the annotation does not exist
214     * this method will return {@code null}.
215     *
216     * @param ast the AST
217     * @return the {@link SuppressWarnings SuppressWarnings} annotation
218     */
219    private static DetailAST getSuppressWarnings(DetailAST ast) {
220        DetailAST annotation = AnnotationUtility.getAnnotation(ast, SUPPRESS_WARNINGS);
221
222        if (annotation == null) {
223            annotation = AnnotationUtility.getAnnotation(ast, FQ_SUPPRESS_WARNINGS);
224        }
225        return annotation;
226    }
227
228    /**
229     * This method looks for a warning that matches a configured expression.
230     * If found it logs a violation at the given line and column number.
231     *
232     * @param lineNo the line number
233     * @param colNum the column number
234     * @param warningText the warning.
235     */
236    private void logMatch(final int lineNo,
237        final int colNum, final String warningText) {
238        final Matcher matcher = format.matcher(warningText);
239        if (matcher.matches()) {
240            log(lineNo, colNum,
241                    MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, warningText);
242        }
243    }
244
245    /**
246     * Find the parent (holder) of the of the warnings (Expr).
247     *
248     * @param annotation the annotation
249     * @return a Token representing the expr.
250     */
251    private static DetailAST findWarningsHolder(final DetailAST annotation) {
252        final DetailAST annValuePair =
253            annotation.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR);
254        final DetailAST annArrayInit;
255
256        if (annValuePair == null) {
257            annArrayInit =
258                    annotation.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT);
259        }
260        else {
261            annArrayInit =
262                    annValuePair.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT);
263        }
264
265        DetailAST warningsHolder = annotation;
266        if (annArrayInit != null) {
267            warningsHolder = annArrayInit;
268        }
269
270        return warningsHolder;
271    }
272
273    /**
274     * Strips a single double quote from the front and back of a string.
275     *
276     * <p>For example:
277     * <br/>
278     * Input String = "unchecked"
279     * <br/>
280     * Output String = unchecked
281     *
282     * @param warning the warning string
283     * @return the string without two quotes
284     */
285    private static String removeQuotes(final String warning) {
286        return warning.substring(1, warning.length() - 1);
287    }
288
289    /**
290     * Recursively walks a conditional expression checking the left
291     * and right sides, checking for matches and
292     * logging violations.
293     *
294     * @param cond a Conditional type
295     * {@link TokenTypes#QUESTION QUESTION}
296     */
297    private void walkConditional(final DetailAST cond) {
298        if (cond.getType() == TokenTypes.QUESTION) {
299            walkConditional(getCondLeft(cond));
300            walkConditional(getCondRight(cond));
301        }
302        else {
303            final String warningText =
304                    removeQuotes(cond.getText());
305            logMatch(cond.getLineNo(), cond.getColumnNo(), warningText);
306        }
307    }
308
309    /**
310     * Retrieves the left side of a conditional.
311     *
312     * @param cond cond a conditional type
313     * {@link TokenTypes#QUESTION QUESTION}
314     * @return either the value
315     *     or another conditional
316     */
317    private static DetailAST getCondLeft(final DetailAST cond) {
318        final DetailAST colon = cond.findFirstToken(TokenTypes.COLON);
319        return colon.getPreviousSibling();
320    }
321
322    /**
323     * Retrieves the right side of a conditional.
324     *
325     * @param cond a conditional type
326     * {@link TokenTypes#QUESTION QUESTION}
327     * @return either the value
328     *     or another conditional
329     */
330    private static DetailAST getCondRight(final DetailAST cond) {
331        final DetailAST colon = cond.findFirstToken(TokenTypes.COLON);
332        return colon.getNextSibling();
333    }
334}