001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2024 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 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} 110 * </p> 111 * <p> 112 * Violation Message Keys: 113 * </p> 114 * <ul> 115 * <li> 116 * {@code suppressed.warning.not.allowed} 117 * </li> 118 * </ul> 119 * 120 * @since 5.0 121 */ 122@StatelessCheck 123public class SuppressWarningsCheck extends AbstractCheck { 124 125 /** 126 * A key is pointing to the warning message text in "messages.properties" 127 * file. 128 */ 129 public static final String MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED = 130 "suppressed.warning.not.allowed"; 131 132 /** {@link SuppressWarnings SuppressWarnings} annotation name. */ 133 private static final String SUPPRESS_WARNINGS = "SuppressWarnings"; 134 135 /** 136 * Fully-qualified {@link SuppressWarnings SuppressWarnings} 137 * annotation name. 138 */ 139 private static final String FQ_SUPPRESS_WARNINGS = 140 "java.lang." + SUPPRESS_WARNINGS; 141 142 /** 143 * Specify the RegExp to match against warnings. Any warning 144 * being suppressed matching this pattern will be flagged. 145 */ 146 private Pattern format = Pattern.compile("^\\s*+$"); 147 148 /** 149 * Setter to specify the RegExp to match against warnings. Any warning 150 * being suppressed matching this pattern will be flagged. 151 * 152 * @param pattern the new pattern 153 * @since 5.0 154 */ 155 public final void setFormat(Pattern pattern) { 156 format = pattern; 157 } 158 159 @Override 160 public final int[] getDefaultTokens() { 161 return getAcceptableTokens(); 162 } 163 164 @Override 165 public final int[] getAcceptableTokens() { 166 return new int[] { 167 TokenTypes.CLASS_DEF, 168 TokenTypes.INTERFACE_DEF, 169 TokenTypes.ENUM_DEF, 170 TokenTypes.ANNOTATION_DEF, 171 TokenTypes.ANNOTATION_FIELD_DEF, 172 TokenTypes.ENUM_CONSTANT_DEF, 173 TokenTypes.PARAMETER_DEF, 174 TokenTypes.VARIABLE_DEF, 175 TokenTypes.METHOD_DEF, 176 TokenTypes.CTOR_DEF, 177 TokenTypes.COMPACT_CTOR_DEF, 178 TokenTypes.RECORD_DEF, 179 }; 180 } 181 182 @Override 183 public int[] getRequiredTokens() { 184 return CommonUtil.EMPTY_INT_ARRAY; 185 } 186 187 @Override 188 public void visitToken(final DetailAST ast) { 189 final DetailAST annotation = getSuppressWarnings(ast); 190 191 if (annotation != null) { 192 final DetailAST warningHolder = 193 findWarningsHolder(annotation); 194 195 final DetailAST token = 196 warningHolder.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR); 197 198 // case like '@SuppressWarnings(value = UNUSED)' 199 final DetailAST parent = Objects.requireNonNullElse(token, warningHolder); 200 DetailAST warning = parent.findFirstToken(TokenTypes.EXPR); 201 202 // rare case with empty array ex: @SuppressWarnings({}) 203 if (warning == null) { 204 // check to see if empty warnings are forbidden -- are by default 205 logMatch(warningHolder, ""); 206 } 207 else { 208 while (warning != null) { 209 if (warning.getType() == TokenTypes.EXPR) { 210 final DetailAST fChild = warning.getFirstChild(); 211 switch (fChild.getType()) { 212 // typical case 213 case TokenTypes.STRING_LITERAL: 214 final String warningText = 215 removeQuotes(warning.getFirstChild().getText()); 216 logMatch(warning, warningText); 217 break; 218 // conditional case 219 // ex: 220 // @SuppressWarnings((false) ? (true) ? "unchecked" : "foo" : "unused") 221 case TokenTypes.QUESTION: 222 walkConditional(fChild); 223 break; 224 default: 225 // Known limitation: cases like @SuppressWarnings("un" + "used") or 226 // @SuppressWarnings((String) "unused") are not properly supported, 227 // but they should not cause exceptions. 228 // Also constant as param 229 // ex: public static final String UNCHECKED = "unchecked"; 230 // @SuppressWarnings(UNCHECKED) 231 // or 232 // @SuppressWarnings(SomeClass.UNCHECKED) 233 } 234 } 235 warning = warning.getNextSibling(); 236 } 237 } 238 } 239 } 240 241 /** 242 * Gets the {@link SuppressWarnings SuppressWarnings} annotation 243 * that is annotating the AST. If the annotation does not exist 244 * this method will return {@code null}. 245 * 246 * @param ast the AST 247 * @return the {@link SuppressWarnings SuppressWarnings} annotation 248 */ 249 private static DetailAST getSuppressWarnings(DetailAST ast) { 250 DetailAST annotation = AnnotationUtil.getAnnotation(ast, SUPPRESS_WARNINGS); 251 252 if (annotation == null) { 253 annotation = AnnotationUtil.getAnnotation(ast, FQ_SUPPRESS_WARNINGS); 254 } 255 return annotation; 256 } 257 258 /** 259 * This method looks for a warning that matches a configured expression. 260 * If found it logs a violation at the given AST. 261 * 262 * @param ast the location to place the violation 263 * @param warningText the warning. 264 */ 265 private void logMatch(DetailAST ast, final String warningText) { 266 final Matcher matcher = format.matcher(warningText); 267 if (matcher.matches()) { 268 log(ast, 269 MSG_KEY_SUPPRESSED_WARNING_NOT_ALLOWED, warningText); 270 } 271 } 272 273 /** 274 * Find the parent (holder) of the of the warnings (Expr). 275 * 276 * @param annotation the annotation 277 * @return a Token representing the expr. 278 */ 279 private static DetailAST findWarningsHolder(final DetailAST annotation) { 280 final DetailAST annValuePair = 281 annotation.findFirstToken(TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR); 282 283 final DetailAST annArrayInitParent = Objects.requireNonNullElse(annValuePair, annotation); 284 final DetailAST annArrayInit = annArrayInitParent 285 .findFirstToken(TokenTypes.ANNOTATION_ARRAY_INIT); 286 return Objects.requireNonNullElse(annArrayInit, annotation); 287 } 288 289 /** 290 * Strips a single double quote from the front and back of a string. 291 * 292 * <p>For example:</p> 293 * <pre> 294 * Input String = "unchecked" 295 * </pre> 296 * Output String = unchecked 297 * 298 * @param warning the warning string 299 * @return the string without two quotes 300 */ 301 private static String removeQuotes(final String warning) { 302 return warning.substring(1, warning.length() - 1); 303 } 304 305 /** 306 * Recursively walks a conditional expression checking the left 307 * and right sides, checking for matches and 308 * logging violations. 309 * 310 * @param cond a Conditional type 311 * {@link TokenTypes#QUESTION QUESTION} 312 * @noinspection TailRecursion 313 * @noinspectionreason TailRecursion - until issue #14814 314 */ 315 private void walkConditional(final DetailAST cond) { 316 if (cond.getType() == TokenTypes.QUESTION) { 317 walkConditional(getCondLeft(cond)); 318 walkConditional(getCondRight(cond)); 319 } 320 else { 321 final String warningText = 322 removeQuotes(cond.getText()); 323 logMatch(cond, warningText); 324 } 325 } 326 327 /** 328 * Retrieves the left side of a conditional. 329 * 330 * @param cond cond a conditional type 331 * {@link TokenTypes#QUESTION QUESTION} 332 * @return either the value 333 * or another conditional 334 */ 335 private static DetailAST getCondLeft(final DetailAST cond) { 336 final DetailAST colon = cond.findFirstToken(TokenTypes.COLON); 337 return colon.getPreviousSibling(); 338 } 339 340 /** 341 * Retrieves the right side of a conditional. 342 * 343 * @param cond a conditional type 344 * {@link TokenTypes#QUESTION QUESTION} 345 * @return either the value 346 * or another conditional 347 */ 348 private static DetailAST getCondRight(final DetailAST cond) { 349 final DetailAST colon = cond.findFirstToken(TokenTypes.COLON); 350 return colon.getNextSibling(); 351 } 352 353}