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