001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2023 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 default: 246 // Known limitation: cases like @SuppressWarnings("un" + "used") or 247 // @SuppressWarnings((String) "unused") are not properly supported, 248 // but they should not cause exceptions. 249 // Also constant as param 250 // ex: public static final String UNCHECKED = "unchecked"; 251 // @SuppressWarnings(UNCHECKED) 252 // or 253 // @SuppressWarnings(SomeClass.UNCHECKED) 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 304 final DetailAST annArrayInitParent = Objects.requireNonNullElse(annValuePair, annotation); 305 final DetailAST annArrayInit = annArrayInitParent 306 .findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT); 307 return Objects.requireNonNullElse(annArrayInit, annotation); 308 } 309 310 /** 311 * Strips a single double quote from the front and back of a string. 312 * 313 * <p>For example:</p> 314 * <pre> 315 * Input String = "unchecked" 316 * </pre> 317 * Output String = unchecked 318 * 319 * @param warning the warning string 320 * @return the string without two quotes 321 */ 322 private static String removeQuotes(final String warning) { 323 return warning.substring(1, warning.length() - 1); 324 } 325 326 /** 327 * Recursively walks a conditional expression checking the left 328 * and right sides, checking for matches and 329 * logging violations. 330 * 331 * @param cond a Conditional type 332 * {@link TokenTypes#QUESTION QUESTION} 333 */ 334 private void walkConditional(final DetailAST cond) { 335 if (cond.getType() == TokenTypes.QUESTION) { 336 walkConditional(getCondLeft(cond)); 337 walkConditional(getCondRight(cond)); 338 } 339 else { 340 final String warningText = 341 removeQuotes(cond.getText()); 342 logMatch(cond, warningText); 343 } 344 } 345 346 /** 347 * Retrieves the left side of a conditional. 348 * 349 * @param cond cond a conditional type 350 * {@link TokenTypes#QUESTION QUESTION} 351 * @return either the value 352 * or another conditional 353 */ 354 private static DetailAST getCondLeft(final DetailAST cond) { 355 final DetailAST colon = cond.findFirstToken(TokenTypes.COLON); 356 return colon.getPreviousSibling(); 357 } 358 359 /** 360 * Retrieves the right side of a conditional. 361 * 362 * @param cond a conditional type 363 * {@link TokenTypes#QUESTION QUESTION} 364 * @return either the value 365 * or another conditional 366 */ 367 private static DetailAST getCondRight(final DetailAST cond) { 368 final DetailAST colon = cond.findFirstToken(TokenTypes.COLON); 369 return colon.getNextSibling(); 370 } 371 372}