001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2015 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;
023
024import org.apache.commons.lang3.ArrayUtils;
025
026import com.puppycrawl.tools.checkstyle.api.DetailAST;
027import com.puppycrawl.tools.checkstyle.api.TokenTypes;
028import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck;
029import com.puppycrawl.tools.checkstyle.utils.AnnotationUtility;
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 AbstractFormatCheck#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 com.puppycrawl.tools.checkstyle.api.Check#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 AbstractFormatCheck {
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    /**
111     * Ctor that specifies the default for the format property
112     * as specified in the class javadocs.
113     */
114    public SuppressWarningsCheck() {
115        super("^$|^\\s+$");
116    }
117
118    @Override
119    public final int[] getDefaultTokens() {
120        return getAcceptableTokens();
121    }
122
123    @Override
124    public final int[] getAcceptableTokens() {
125        return new int[] {
126            TokenTypes.CLASS_DEF,
127            TokenTypes.INTERFACE_DEF,
128            TokenTypes.ENUM_DEF,
129            TokenTypes.ANNOTATION_DEF,
130            TokenTypes.ANNOTATION_FIELD_DEF,
131            TokenTypes.ENUM_CONSTANT_DEF,
132            TokenTypes.PARAMETER_DEF,
133            TokenTypes.VARIABLE_DEF,
134            TokenTypes.METHOD_DEF,
135            TokenTypes.CTOR_DEF,
136        };
137    }
138
139    @Override
140    public int[] getRequiredTokens() {
141        return ArrayUtils.EMPTY_INT_ARRAY;
142    }
143
144    @Override
145    public void visitToken(final DetailAST ast) {
146        final DetailAST annotation = getSuppressWarnings(ast);
147
148        if (annotation == null) {
149            return;
150        }
151
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            // case like '@SuppressWarnings(value = UNUSED)'
161            warning = token.findFirstToken(TokenTypes.EXPR);
162        }
163        else {
164            warning = warningHolder.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            return;
173        }
174
175        while (warning != null) {
176            if (warning.getType() == TokenTypes.EXPR) {
177                final DetailAST fChild = warning.getFirstChild();
178                switch (fChild.getType()) {
179                    //typical case
180                    case TokenTypes.STRING_LITERAL:
181                        final String warningText =
182                            removeQuotes(warning.getFirstChild().getText());
183                        logMatch(warning.getLineNo(),
184                                warning.getColumnNo(), warningText);
185                        break;
186                    // conditional case
187                    // ex: @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) or @SuppressWarnings(SomeClass.UNCHECKED)
194                    case TokenTypes.IDENT:
195                    case TokenTypes.DOT:
196                        break;
197                    default:
198                        // Known limitation: cases like @SuppressWarnings("un" + "used") or
199                        // @SuppressWarnings((String) "unused") are not properly supported,
200                        // but they should not cause exceptions.
201                }
202            }
203            warning = warning.getNextSibling();
204        }
205    }
206
207    /**
208     * Gets the {@link SuppressWarnings SuppressWarnings} annotation
209     * that is annotating the AST.  If the annotation does not exist
210     * this method will return {@code null}.
211     *
212     * @param ast the AST
213     * @return the {@link SuppressWarnings SuppressWarnings} annotation
214     */
215    private static DetailAST getSuppressWarnings(DetailAST ast) {
216        final DetailAST annotation = AnnotationUtility.getAnnotation(
217            ast, SUPPRESS_WARNINGS);
218
219        if (annotation == null) {
220            return AnnotationUtility.getAnnotation(ast, FQ_SUPPRESS_WARNINGS);
221        }
222        else {
223            return annotation;
224        }
225    }
226
227    /**
228     * This method looks for a warning that matches a configured expression.
229     * If found it logs a violation at the given line and column number.
230     *
231     * @param lineNo the line number
232     * @param colNum the column number
233     * @param warningText the warning.
234     */
235    private void logMatch(final int lineNo,
236        final int colNum, final String warningText) {
237        final Matcher matcher = getRegexp().matcher(warningText);
238        if (matcher.matches()) {
239            log(lineNo, colNum,
240                    MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, warningText);
241        }
242    }
243
244    /**
245     * Find the parent (holder) of the of the warnings (Expr).
246     *
247     * @param annotation the annotation
248     * @return a Token representing the expr.
249     */
250    private static DetailAST findWarningsHolder(final DetailAST annotation) {
251        final DetailAST annValuePair =
252            annotation.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR);
253        final DetailAST annArrayInit;
254
255        if (annValuePair != null) {
256            annArrayInit =
257                annValuePair.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT);
258        }
259        else {
260            annArrayInit =
261                annotation.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT);
262        }
263
264        if (annArrayInit != null) {
265            return annArrayInit;
266        }
267
268        return annotation;
269    }
270
271    /**
272     * Strips a single double quote from the front and back of a string.
273     *
274     * <p>For example:
275     * <br/>
276     * Input String = "unchecked"
277     * <br/>
278     * Output String = unchecked
279     *
280     * @param warning the warning string
281     * @return the string without two quotes
282     */
283    private static String removeQuotes(final String warning) {
284        return warning.substring(1, warning.length() - 1);
285    }
286
287    /**
288     * Recursively walks a conditional expression checking the left
289     * and right sides, checking for matches and
290     * logging violations.
291     *
292     * @param cond a Conditional type
293     * {@link TokenTypes#QUESTION QUESTION}
294     */
295    private void walkConditional(final DetailAST cond) {
296        if (cond.getType() != TokenTypes.QUESTION) {
297            final String warningText =
298                removeQuotes(cond.getText());
299            logMatch(cond.getLineNo(), cond.getColumnNo(), warningText);
300            return;
301        }
302
303        walkConditional(getCondLeft(cond));
304        walkConditional(getCondRight(cond));
305    }
306
307    /**
308     * Retrieves the left side of a conditional.
309     *
310     * @param cond cond a conditional type
311     * {@link TokenTypes#QUESTION QUESTION}
312     * @return either the value
313     *     or another conditional
314     */
315    private static DetailAST getCondLeft(final DetailAST cond) {
316        final DetailAST colon = cond.findFirstToken(TokenTypes.COLON);
317        return colon.getPreviousSibling();
318    }
319
320    /**
321     * Retrieves the right side of a conditional.
322     *
323     * @param cond a conditional type
324     * {@link TokenTypes#QUESTION QUESTION}
325     * @return either the value
326     *     or another conditional
327     */
328    private static DetailAST getCondRight(final DetailAST cond) {
329        final DetailAST colon = cond.findFirstToken(TokenTypes.COLON);
330        return colon.getNextSibling();
331    }
332}