001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2018 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.StatelessCheck; 026import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 027import com.puppycrawl.tools.checkstyle.api.DetailAST; 028import com.puppycrawl.tools.checkstyle.api.TokenTypes; 029import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil; 030import com.puppycrawl.tools.checkstyle.utils.CommonUtil; 031 032/** 033 * <p> 034 * This check allows you to specify what warnings that 035 * {@link SuppressWarnings SuppressWarnings} is not 036 * allowed to suppress. You can also specify a list 037 * of TokenTypes that the configured warning(s) cannot 038 * be suppressed on. 039 * </p> 040 * 041 * <p> 042 * The {@link #setFormat warnings} property is a 043 * regex pattern. Any warning being suppressed matching 044 * this pattern will be flagged. 045 * </p> 046 * 047 * <p> 048 * By default, any warning specified will be disallowed on 049 * all legal TokenTypes unless otherwise specified via 050 * the 051 * {@link AbstractCheck#setTokens(String[]) tokens} 052 * property. 053 * 054 * Also, by default warnings that are empty strings or all 055 * whitespace (regex: ^$|^\s+$) are flagged. By specifying, 056 * the format property these defaults no longer apply. 057 * </p> 058 * 059 * <p>Limitations: This check does not consider conditionals 060 * inside the SuppressWarnings annotation. <br> 061 * For example: 062 * {@code @SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused")}. 063 * According to the above example, the "unused" warning is being suppressed 064 * not the "unchecked" or "foo" warnings. All of these warnings will be 065 * considered and matched against regardless of what the conditional 066 * evaluates to. 067 * <br> 068 * The check also does not support code like {@code @SuppressWarnings("un" + "used")}, 069 * {@code @SuppressWarnings((String) "unused")} or 070 * {@code @SuppressWarnings({('u' + (char)'n') + (""+("used" + (String)"")),})}. 071 * </p> 072 * 073 * <p>This check can be configured so that the "unchecked" 074 * and "unused" warnings cannot be suppressed on 075 * anything but variable and parameter declarations. 076 * See below of an example. 077 * </p> 078 * 079 * <pre> 080 * <module name="SuppressWarnings"> 081 * <property name="format" 082 * value="^unchecked$|^unused$"/> 083 * <property name="tokens" 084 * value=" 085 * CLASS_DEF,INTERFACE_DEF,ENUM_DEF, 086 * ANNOTATION_DEF,ANNOTATION_FIELD_DEF, 087 * ENUM_CONSTANT_DEF,METHOD_DEF,CTOR_DEF 088 * "/> 089 * </module> 090 * </pre> 091 */ 092@StatelessCheck 093public class SuppressWarningsCheck extends AbstractCheck { 094 095 /** 096 * A key is pointing to the warning message text in "messages.properties" 097 * file. 098 */ 099 public static final String MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED = 100 "suppressed.warning.not.allowed"; 101 102 /** {@link SuppressWarnings SuppressWarnings} annotation name. */ 103 private static final String SUPPRESS_WARNINGS = "SuppressWarnings"; 104 105 /** 106 * Fully-qualified {@link SuppressWarnings SuppressWarnings} 107 * annotation name. 108 */ 109 private static final String FQ_SUPPRESS_WARNINGS = 110 "java.lang." + SUPPRESS_WARNINGS; 111 112 /** The regexp to match against. */ 113 private Pattern format = Pattern.compile("^$|^\\s+$"); 114 115 /** 116 * Set the format for the specified regular expression. 117 * @param pattern the new pattern 118 */ 119 public final void setFormat(Pattern pattern) { 120 format = pattern; 121 } 122 123 @Override 124 public final int[] getDefaultTokens() { 125 return getAcceptableTokens(); 126 } 127 128 @Override 129 public final int[] getAcceptableTokens() { 130 return new int[] { 131 TokenTypes.CLASS_DEF, 132 TokenTypes.INTERFACE_DEF, 133 TokenTypes.ENUM_DEF, 134 TokenTypes.ANNOTATION_DEF, 135 TokenTypes.ANNOTATION_FIELD_DEF, 136 TokenTypes.ENUM_CONSTANT_DEF, 137 TokenTypes.PARAMETER_DEF, 138 TokenTypes.VARIABLE_DEF, 139 TokenTypes.METHOD_DEF, 140 TokenTypes.CTOR_DEF, 141 }; 142 } 143 144 @Override 145 public int[] getRequiredTokens() { 146 return CommonUtil.EMPTY_INT_ARRAY; 147 } 148 149 @Override 150 public void visitToken(final DetailAST ast) { 151 final DetailAST annotation = getSuppressWarnings(ast); 152 153 if (annotation != null) { 154 final DetailAST warningHolder = 155 findWarningsHolder(annotation); 156 157 final DetailAST token = 158 warningHolder.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR); 159 DetailAST warning; 160 161 if (token == null) { 162 warning = warningHolder.findFirstToken(TokenTypes.EXPR); 163 } 164 else { 165 // case like '@SuppressWarnings(value = UNUSED)' 166 warning = token.findFirstToken(TokenTypes.EXPR); 167 } 168 169 //rare case with empty array ex: @SuppressWarnings({}) 170 if (warning == null) { 171 //check to see if empty warnings are forbidden -- are by default 172 logMatch(warningHolder, ""); 173 } 174 else { 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, 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 = AnnotationUtil.getAnnotation(ast, SUPPRESS_WARNINGS); 221 222 if (annotation == null) { 223 annotation = AnnotationUtil.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 AST. 231 * 232 * @param ast the location to place the violation 233 * @param warningText the warning. 234 */ 235 private void logMatch(DetailAST ast, final String warningText) { 236 final Matcher matcher = format.matcher(warningText); 237 if (matcher.matches()) { 238 log(ast, 239 MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, warningText); 240 } 241 } 242 243 /** 244 * Find the parent (holder) of the of the warnings (Expr). 245 * 246 * @param annotation the annotation 247 * @return a Token representing the expr. 248 */ 249 private static DetailAST findWarningsHolder(final DetailAST annotation) { 250 final DetailAST annValuePair = 251 annotation.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR); 252 final DetailAST annArrayInit; 253 254 if (annValuePair == null) { 255 annArrayInit = 256 annotation.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT); 257 } 258 else { 259 annArrayInit = 260 annValuePair.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT); 261 } 262 263 DetailAST warningsHolder = annotation; 264 if (annArrayInit != null) { 265 warningsHolder = annArrayInit; 266 } 267 268 return warningsHolder; 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 walkConditional(getCondLeft(cond)); 298 walkConditional(getCondRight(cond)); 299 } 300 else { 301 final String warningText = 302 removeQuotes(cond.getText()); 303 logMatch(cond, warningText); 304 } 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 333}