001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2020 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 * Allows to specify what warnings that 035 * {@code @SuppressWarnings} is not allowed to suppress. 036 * You can also specify a list of TokenTypes that 037 * the configured warning(s) cannot be suppressed on. 038 * </p> 039 * <p> 040 * Limitations: This check does not consider conditionals 041 * inside the @SuppressWarnings annotation. 042 * </p> 043 * <p> 044 * For example: 045 * {@code @SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused")}. 046 * According to the above example, the "unused" warning is being suppressed 047 * not the "unchecked" or "foo" warnings. All of these warnings will be 048 * considered and matched against regardless of what the conditional 049 * evaluates to. 050 * The check also does not support code like {@code @SuppressWarnings("un" + "used")}, 051 * {@code @SuppressWarnings((String) "unused")} or 052 * {@code @SuppressWarnings({('u' + (char)'n') + (""+("used" + (String)"")),})}. 053 * </p> 054 * <p> 055 * By default, any warning specified will be disallowed on 056 * all legal TokenTypes unless otherwise specified via 057 * the tokens property. 058 * </p> 059 * <p> 060 * Also, by default warnings that are empty strings or all 061 * whitespace (regex: ^$|^\s+$) are flagged. By specifying, 062 * the format property these defaults no longer apply. 063 * </p> 064 * <p>This check can be configured so that the "unchecked" 065 * and "unused" warnings cannot be suppressed on 066 * anything but variable and parameter declarations. 067 * See below of an example. 068 * </p> 069 * <ul> 070 * <li> 071 * Property {@code format} - Specify the RegExp to match against warnings. Any warning 072 * being suppressed matching this pattern will be flagged. 073 * Type is {@code java.util.regex.Pattern}. 074 * Default value is {@code "^\s*+$"}. 075 * </li> 076 * <li> 077 * Property {@code tokens} - tokens to check 078 * Type is {@code int[]}. 079 * Default value is: 080 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#CLASS_DEF"> 081 * CLASS_DEF</a>, 082 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#INTERFACE_DEF"> 083 * INTERFACE_DEF</a>, 084 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ENUM_DEF"> 085 * ENUM_DEF</a>, 086 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ANNOTATION_DEF"> 087 * ANNOTATION_DEF</a>, 088 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ANNOTATION_FIELD_DEF"> 089 * ANNOTATION_FIELD_DEF</a>, 090 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ENUM_CONSTANT_DEF"> 091 * ENUM_CONSTANT_DEF</a>, 092 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#PARAMETER_DEF"> 093 * PARAMETER_DEF</a>, 094 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#VARIABLE_DEF"> 095 * VARIABLE_DEF</a>, 096 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#METHOD_DEF"> 097 * METHOD_DEF</a>, 098 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#CTOR_DEF"> 099 * CTOR_DEF</a>. 100 * </li> 101 * </ul> 102 * <p> 103 * To configure the check: 104 * </p> 105 * <pre> 106 * <module name="SuppressWarnings"/> 107 * </pre> 108 * <p> 109 * To configure the check so that the "unchecked" and "unused" 110 * warnings cannot be suppressed on anything but variable and parameter declarations. 111 * </p> 112 * <pre> 113 * <module name="SuppressWarnings"> 114 * <property name="format" 115 * value="^unchecked$|^unused$"/> 116 * <property name="tokens" 117 * value=" 118 * CLASS_DEF,INTERFACE_DEF,ENUM_DEF, 119 * ANNOTATION_DEF,ANNOTATION_FIELD_DEF, 120 * ENUM_CONSTANT_DEF,METHOD_DEF,CTOR_DEF 121 * "/> 122 * </module> 123 * </pre> 124 * <p> 125 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} 126 * </p> 127 * <p> 128 * Violation Message Keys: 129 * </p> 130 * <ul> 131 * <li> 132 * {@code suppressed.warning.not.allowed} 133 * </li> 134 * </ul> 135 * 136 * @since 5.0 137 */ 138@StatelessCheck 139public class SuppressWarningsCheck extends AbstractCheck { 140 141 /** 142 * A key is pointing to the warning message text in "messages.properties" 143 * file. 144 */ 145 public static final String MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED = 146 "suppressed.warning.not.allowed"; 147 148 /** {@link SuppressWarnings SuppressWarnings} annotation name. */ 149 private static final String SUPPRESS_WARNINGS = "SuppressWarnings"; 150 151 /** 152 * Fully-qualified {@link SuppressWarnings SuppressWarnings} 153 * annotation name. 154 */ 155 private static final String FQ_SUPPRESS_WARNINGS = 156 "java.lang." + SUPPRESS_WARNINGS; 157 158 /** 159 * Specify the RegExp to match against warnings. Any warning 160 * being suppressed matching this pattern will be flagged. 161 */ 162 private Pattern format = Pattern.compile("^\\s*+$"); 163 164 /** 165 * Setter to specify the RegExp to match against warnings. Any warning 166 * being suppressed matching this pattern will be flagged. 167 * 168 * @param pattern the new pattern 169 */ 170 public final void setFormat(Pattern pattern) { 171 format = pattern; 172 } 173 174 @Override 175 public final int[] getDefaultTokens() { 176 return getAcceptableTokens(); 177 } 178 179 @Override 180 public final int[] getAcceptableTokens() { 181 return new int[] { 182 TokenTypes.CLASS_DEF, 183 TokenTypes.INTERFACE_DEF, 184 TokenTypes.ENUM_DEF, 185 TokenTypes.ANNOTATION_DEF, 186 TokenTypes.ANNOTATION_FIELD_DEF, 187 TokenTypes.ENUM_CONSTANT_DEF, 188 TokenTypes.PARAMETER_DEF, 189 TokenTypes.VARIABLE_DEF, 190 TokenTypes.METHOD_DEF, 191 TokenTypes.CTOR_DEF, 192 }; 193 } 194 195 @Override 196 public int[] getRequiredTokens() { 197 return CommonUtil.EMPTY_INT_ARRAY; 198 } 199 200 @Override 201 public void visitToken(final DetailAST ast) { 202 final DetailAST annotation = getSuppressWarnings(ast); 203 204 if (annotation != null) { 205 final DetailAST warningHolder = 206 findWarningsHolder(annotation); 207 208 final DetailAST token = 209 warningHolder.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR); 210 DetailAST warning; 211 212 if (token == null) { 213 warning = warningHolder.findFirstToken(TokenTypes.EXPR); 214 } 215 else { 216 // case like '@SuppressWarnings(value = UNUSED)' 217 warning = token.findFirstToken(TokenTypes.EXPR); 218 } 219 220 // rare case with empty array ex: @SuppressWarnings({}) 221 if (warning == null) { 222 // check to see if empty warnings are forbidden -- are by default 223 logMatch(warningHolder, ""); 224 } 225 else { 226 while (warning != null) { 227 if (warning.getType() == TokenTypes.EXPR) { 228 final DetailAST fChild = warning.getFirstChild(); 229 switch (fChild.getType()) { 230 // typical case 231 case TokenTypes.STRING_LITERAL: 232 final String warningText = 233 removeQuotes(warning.getFirstChild().getText()); 234 logMatch(warning, warningText); 235 break; 236 // conditional case 237 // ex: 238 // @SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused") 239 case TokenTypes.QUESTION: 240 walkConditional(fChild); 241 break; 242 // param in constant case 243 // ex: public static final String UNCHECKED = "unchecked"; 244 // @SuppressWarnings(UNCHECKED) 245 // or 246 // @SuppressWarnings(SomeClass.UNCHECKED) 247 case TokenTypes.IDENT: 248 case TokenTypes.DOT: 249 break; 250 default: 251 // Known limitation: cases like @SuppressWarnings("un" + "used") or 252 // @SuppressWarnings((String) "unused") are not properly supported, 253 // but they should not cause exceptions. 254 } 255 } 256 warning = warning.getNextSibling(); 257 } 258 } 259 } 260 } 261 262 /** 263 * Gets the {@link SuppressWarnings SuppressWarnings} annotation 264 * that is annotating the AST. If the annotation does not exist 265 * this method will return {@code null}. 266 * 267 * @param ast the AST 268 * @return the {@link SuppressWarnings SuppressWarnings} annotation 269 */ 270 private static DetailAST getSuppressWarnings(DetailAST ast) { 271 DetailAST annotation = AnnotationUtil.getAnnotation(ast, SUPPRESS_WARNINGS); 272 273 if (annotation == null) { 274 annotation = AnnotationUtil.getAnnotation(ast, FQ_SUPPRESS_WARNINGS); 275 } 276 return annotation; 277 } 278 279 /** 280 * This method looks for a warning that matches a configured expression. 281 * If found it logs a violation at the given AST. 282 * 283 * @param ast the location to place the violation 284 * @param warningText the warning. 285 */ 286 private void logMatch(DetailAST ast, final String warningText) { 287 final Matcher matcher = format.matcher(warningText); 288 if (matcher.matches()) { 289 log(ast, 290 MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, warningText); 291 } 292 } 293 294 /** 295 * Find the parent (holder) of the of the warnings (Expr). 296 * 297 * @param annotation the annotation 298 * @return a Token representing the expr. 299 */ 300 private static DetailAST findWarningsHolder(final DetailAST annotation) { 301 final DetailAST annValuePair = 302 annotation.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR); 303 final DetailAST annArrayInit; 304 305 if (annValuePair == null) { 306 annArrayInit = 307 annotation.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT); 308 } 309 else { 310 annArrayInit = 311 annValuePair.findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT); 312 } 313 314 DetailAST warningsHolder = annotation; 315 if (annArrayInit != null) { 316 warningsHolder = annArrayInit; 317 } 318 319 return warningsHolder; 320 } 321 322 /** 323 * Strips a single double quote from the front and back of a string. 324 * 325 * <p>For example: 326 * <br/> 327 * Input String = "unchecked" 328 * <br/> 329 * Output String = unchecked 330 * 331 * @param warning the warning string 332 * @return the string without two quotes 333 */ 334 private static String removeQuotes(final String warning) { 335 return warning.substring(1, warning.length() - 1); 336 } 337 338 /** 339 * Recursively walks a conditional expression checking the left 340 * and right sides, checking for matches and 341 * logging violations. 342 * 343 * @param cond a Conditional type 344 * {@link TokenTypes#QUESTION QUESTION} 345 */ 346 private void walkConditional(final DetailAST cond) { 347 if (cond.getType() == TokenTypes.QUESTION) { 348 walkConditional(getCondLeft(cond)); 349 walkConditional(getCondRight(cond)); 350 } 351 else { 352 final String warningText = 353 removeQuotes(cond.getText()); 354 logMatch(cond, warningText); 355 } 356 } 357 358 /** 359 * Retrieves the left side of a conditional. 360 * 361 * @param cond cond a conditional type 362 * {@link TokenTypes#QUESTION QUESTION} 363 * @return either the value 364 * or another conditional 365 */ 366 private static DetailAST getCondLeft(final DetailAST cond) { 367 final DetailAST colon = cond.findFirstToken(TokenTypes.COLON); 368 return colon.getPreviousSibling(); 369 } 370 371 /** 372 * Retrieves the right side of a conditional. 373 * 374 * @param cond a conditional type 375 * {@link TokenTypes#QUESTION QUESTION} 376 * @return either the value 377 * or another conditional 378 */ 379 private static DetailAST getCondRight(final DetailAST cond) { 380 final DetailAST colon = cond.findFirstToken(TokenTypes.COLON); 381 return colon.getNextSibling(); 382 } 383 384}