001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code 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.filters; 021 022import java.util.Collections; 023import java.util.HashSet; 024import java.util.Objects; 025import java.util.Set; 026 027import com.puppycrawl.tools.checkstyle.TreeWalkerAuditEvent; 028import com.puppycrawl.tools.checkstyle.TreeWalkerFilter; 029import com.puppycrawl.tools.checkstyle.api.AutomaticBean; 030import com.puppycrawl.tools.checkstyle.api.CheckstyleException; 031import com.puppycrawl.tools.checkstyle.api.ExternalResourceHolder; 032import com.puppycrawl.tools.checkstyle.utils.FilterUtil; 033 034/** 035 * <p> 036 * Filter {@code SuppressionXpathFilter} works as 037 * <a href="https://checkstyle.org/config_filters.html#SuppressionFilter">SuppressionFilter</a>. 038 * Additionally, filter processes {@code suppress-xpath} elements, 039 * which contains xpath-expressions. Xpath-expressions are queries for 040 * suppressed nodes inside the AST tree. 041 * </p> 042 * <p> 043 * Currently, filter does not support the following checks: 044 * </p> 045 * <ul id="SuppressionXpathFilter_IncompatibleChecks"> 046 * <li> 047 * NoCodeInFile (reason is that AST is not generated for a file not containing code) 048 * </li> 049 * <li> 050 * Regexp (reason is at 051 * <a href="https://github.com/checkstyle/checkstyle/issues/7759#issuecomment-605525287"> #7759</a>) 052 * </li> 053 * <li> 054 * RegexpSinglelineJava (reason is at 055 * <a href="https://github.com/checkstyle/checkstyle/issues/7759#issuecomment-605525287"> #7759</a>) 056 * </li> 057 * </ul> 058 * <p> 059 * Also, the filter does not support suppressions inside javadoc reported by Javadoc checks: 060 * </p> 061 * <ul id="SuppressionXpathFilter_JavadocChecks"> 062 * <li> 063 * AtclauseOrder 064 * </li> 065 * <li> 066 * JavadocBlockTagLocation 067 * </li> 068 * <li> 069 * JavadocMethod 070 * </li> 071 * <li> 072 * JavadocMissingLeadingAsterisk 073 * </li> 074 * <li> 075 * JavadocMissingWhitespaceAfterAsterisk 076 * </li> 077 * <li> 078 * JavadocParagraph 079 * </li> 080 * <li> 081 * JavadocStyle 082 * </li> 083 * <li> 084 * JavadocTagContinuationIndentation 085 * </li> 086 * <li> 087 * JavadocType 088 * </li> 089 * <li> 090 * MissingDeprecated 091 * </li> 092 * <li> 093 * NonEmptyAtclauseDescription 094 * </li> 095 * <li> 096 * RequireEmptyLineBeforeBlockTagGroup 097 * </li> 098 * <li> 099 * SingleLineJavadoc 100 * </li> 101 * <li> 102 * SummaryJavadoc 103 * </li> 104 * <li> 105 * WriteTag 106 * </li> 107 * </ul> 108 * <p> 109 * Note, that support for these Checks will be available after resolving issue 110 * <a href="https://github.com/checkstyle/checkstyle/issues/5770">#5770</a>. 111 * </p> 112 * <p> 113 * Currently, filter supports the following xpath axes: 114 * </p> 115 * <ul> 116 * <li> 117 * ancestor 118 * </li> 119 * <li> 120 * ancestor-or-self 121 * </li> 122 * <li> 123 * attribute 124 * </li> 125 * <li> 126 * child 127 * </li> 128 * <li> 129 * descendant 130 * </li> 131 * <li> 132 * descendant-or-self 133 * </li> 134 * <li> 135 * following 136 * </li> 137 * <li> 138 * following-sibling 139 * </li> 140 * <li> 141 * parent 142 * </li> 143 * <li> 144 * preceding 145 * </li> 146 * <li> 147 * preceding-sibling 148 * </li> 149 * <li> 150 * self 151 * </li> 152 * </ul> 153 * <p> 154 * You can use the command line helper tool to generate xpath suppressions based on your 155 * configuration file and input files. See <a href="https://checkstyle.org/cmdline.html">here</a> 156 * for more details. 157 * </p> 158 * <p> 159 * The suppression file location is checked in following order: 160 * </p> 161 * <ol> 162 * <li> 163 * as a filesystem location 164 * </li> 165 * <li> 166 * if no file found, and the location starts with either {@code http://} or {@code https://}, 167 * then it is interpreted as a URL 168 * </li> 169 * <li> 170 * if no file found, then passed to the {@code ClassLoader.getResource()} method. 171 * </li> 172 * </ol> 173 * <p> 174 * SuppressionXpathFilter can suppress Checks that have Treewalker as parent module. 175 * </p> 176 * <ul> 177 * <li> 178 * Property {@code file} - Specify the location of the <em>suppressions XML document</em> file. 179 * Type is {@code java.lang.String}. 180 * Default value is {@code null}. 181 * </li> 182 * <li> 183 * Property {@code optional} - Control what to do when the file is not existing. 184 * If optional is set to false the file must exist, or else it ends with error. 185 * On the other hand if optional is true and file is not found, the filter accepts all audit events. 186 * Type is {@code boolean}. 187 * Default value is {@code false}. 188 * </li> 189 * </ul> 190 * <p> 191 * For example, the following configuration fragment directs the Checker to use a 192 * {@code SuppressionXpathFilter} with suppressions file {@code config/suppressions.xml}: 193 * </p> 194 * <pre> 195 * <module name="SuppressionXpathFilter"> 196 * <property name="file" value="config/suppressions.xml"/> 197 * <property name="optional" value="false"/> 198 * </module> 199 * </pre> 200 * <p> 201 * A <a href="https://checkstyle.org/dtds/suppressions_1_2_xpath_experimental.dtd"><em> 202 * suppressions XML document</em></a> 203 * contains a set of {@code suppress} and {@code suppress-xpath} elements, 204 * where each {@code suppress-xpath} element can have the following attributes: 205 * </p> 206 * <ul> 207 * <li> 208 * {@code files} - a <a href="https://checkstyle.org/property_types.html#Pattern">Pattern</a> 209 * matched against the file name associated with an audit event. It is optional. 210 * </li> 211 * <li> 212 * {@code checks} - a <a href="https://checkstyle.org/property_types.html#Pattern">Pattern</a> 213 * matched against the name of the check associated with an audit event. 214 * Optional as long as {@code id} or {@code message} is specified. 215 * </li> 216 * <li> 217 * {@code message} - a <a href="https://checkstyle.org/property_types.html#Pattern">Pattern</a> 218 * matched against the message of the check associated with an audit event. 219 * Optional as long as {@code checks} or {@code id} is specified. 220 * </li> 221 * <li> 222 * {@code id} - a <a href="https://checkstyle.org/property_types.html#String">String</a> matched against 223 * the ID of the check associated with an audit event. 224 * Optional as long as {@code checks} or {@code message} is specified. 225 * </li> 226 * <li> 227 * {@code query} - a <a href="https://checkstyle.org/property_types.html#String">String</a> xpath query. It is optional. 228 * </li> 229 * </ul> 230 * <p> 231 * Each audit event is checked against each {@code suppress} and {@code suppress-xpath} element. 232 * It is suppressed if all specified attributes match against the audit event. 233 * </p> 234 * <p> 235 * ATTENTION: filtering by message is dependant on runtime locale. 236 * If project is running in different languages it is better to avoid filtering by message. 237 * </p> 238 * <p> 239 * The following suppressions XML document directs a {@code SuppressionXpathFilter} to reject 240 * {@code CyclomaticComplexity} violations for all methods with name <i>sayHelloWorld</i> inside 241 * <i>FileOne</i> and <i>FileTwo</i> files: 242 * </p> 243 * <p> 244 * Currently, xpath queries support one type of attribute {@code @text}. {@code @text} - 245 * addresses to the text value of the node. For example: variable name, annotation name, 246 * text content and etc. Only the following token types support {@code @text} attribute: 247 * {@code TokenTypes.IDENT}, {@code TokenTypes.STRING_LITERAL}, {@code TokenTypes.CHAR_LITERAL}, 248 * {@code TokenTypes.NUM_LONG}, {@code TokenTypes.NUM_INT}, {@code TokenTypes.NUM_DOUBLE}, 249 * {@code TokenTypes.NUM_FLOAT}. 250 * These token types were selected because only their text values are different 251 * in content from token type and represent text value from file and can be used 252 * in xpath queries for more accurate results. Other token types always have constant values. 253 * </p> 254 * <pre> 255 * <?xml version="1.0"?> 256 * 257 * <!DOCTYPE suppressions PUBLIC 258 * "-//Checkstyle//DTD SuppressionXpathFilter Experimental Configuration 1.2//EN" 259 * "https://checkstyle.org/dtds/suppressions_1_2_xpath_experimental.dtd"> 260 * 261 * <suppressions> 262 * <suppress-xpath checks="CyclomaticComplexity" 263 * files="FileOne.java,FileTwo.java" 264 * query="//METHOD_DEF[./IDENT[@text='sayHelloWorld']]"/> 265 * </suppressions> 266 * </pre> 267 * <p> 268 * Suppress checks for package definitions: 269 * </p> 270 * <pre> 271 * <suppress-xpath checks=".*" query="/PACKAGE_DEF"/> 272 * </pre> 273 * <p> 274 * Suppress checks for parent element of the first variable definition: 275 * </p> 276 * <pre> 277 * <suppress-xpath checks=".*" query="(//VARIABLE_DEF)[1]/.."/> 278 * </pre> 279 * <p> 280 * Suppress checks for elements which are either class definitions, either method definitions. 281 * </p> 282 * <pre> 283 * <suppress-xpath checks=".*" query="//CLASS_DEF | //METHOD_DEF"/> 284 * </pre> 285 * <p> 286 * Suppress checks for certain methods: 287 * </p> 288 * <pre> 289 * <suppress-xpath checks=".*" query="//METHOD_DEF[./IDENT[@text='getSomeVar' 290 * or @text='setSomeVar']]"/> 291 * </pre> 292 * <p> 293 * Suppress checks for variable <i>testVariable</i> inside <i>testMethod</i> 294 * method inside <i>TestClass</i> class. 295 * </p> 296 * <pre> 297 * <suppress-xpath checks=".*" query="//CLASS_DEF[@text='TestClass'] 298 * //METHOD_DEF[./IDENT[@text='testMethod']] 299 * //VARIABLE_DEF[./IDENT[@text='testVariable']]"/> 300 * </pre> 301 * <p> 302 * In the following sample, violations for {@code LeftCurly} check will be suppressed 303 * for classes with name <i>Main</i> or for methods with name <i>calculate</i>. 304 * </p> 305 * <pre> 306 * <suppress-xpath checks="LeftCurly" query="//CLASS_DEF[./IDENT[@text='Main']]//* 307 * | //METHOD_DEF[./IDENT[@text='calculate']]/*"/> 308 * </pre> 309 * <p> 310 * The following example demonstrates how to suppress {@code RequireThis} violations 311 * for variable <i>age</i> inside <i>changeAge</i> method. 312 * </p> 313 * <pre> 314 * <suppress-xpath checks="RequireThis" 315 * query="//CLASS_DEF[./IDENT[@text='InputTest']] 316 * //METHOD_DEF[./IDENT[@text='changeAge']]//ASSIGN/IDENT[@text='age']"/> 317 * </pre> 318 * <pre> 319 * public class InputTest { 320 * private int age = 23; 321 * 322 * public void changeAge() { 323 * age = 24; //violation will be suppressed 324 * } 325 * } 326 * </pre> 327 * <p> 328 * Suppress {@code IllegalThrows} violations only for methods with name <i>throwsMethod</i> 329 * and only for {@code RuntimeException} exceptions. Double colon is used for axis iterations. 330 * In the following example {@code ancestor} axis is used to iterate all ancestor nodes 331 * of the current node with type {@code METHOD_DEF} and name <i>throwsMethod</i>. 332 * Please read more about xpath axes at <a href="https://www.w3schools.com/xml/xpath_axes.asp"> 333 * W3Schools Xpath Axes</a>. 334 * </p> 335 * <pre> 336 * <suppress-xpath checks="IllegalThrows" query="//LITERAL_THROWS 337 * /IDENT[@text='RuntimeException' and 338 * ./ancestor::METHOD_DEF[./IDENT[@text='throwsMethod']]]"/> 339 * </pre> 340 * <pre> 341 * public class InputTest { 342 * public void throwsMethod() throws RuntimeException { // violation will be suppressed 343 * } 344 * 345 * public void sampleMethod() throws RuntimeException { // will throw violation here 346 * } 347 * } 348 * </pre> 349 * <p> 350 * The following sample demonstrates how to suppress all violations for method 351 * itself and all descendants. {@code descendant-or-self} axis iterates through 352 * current node and all children nodes at any level. Keyword {@code node()} 353 * selects node elements. Please read more about xpath syntax at 354 * <a href="https://www.w3schools.com/xml/xpath_syntax.asp">W3Schools Xpath Syntax</a>. 355 * </p> 356 * <pre> 357 * <suppress-xpath checks=".*" query="//METHOD_DEF[./IDENT[@text='legacyMethod']] 358 * /descendant-or-self::node()"/> 359 * </pre> 360 * <p> 361 * Some elements can be suppressed in different ways. For example, to suppress 362 * violation on variable {@code wordCount} in following code: 363 * </p> 364 * <pre> 365 * public class InputTest { 366 * private int wordCount = 11; 367 * } 368 * </pre> 369 * <p> 370 * You need to look at AST of such code by our CLI tool: 371 * </p> 372 * <pre> 373 * $ java -jar checkstyle-X.XX-all.jar -t InputTest.java 374 * CLASS_DEF -> CLASS_DEF [1:0] 375 * |--MODIFIERS -> MODIFIERS [1:0] 376 * | `--LITERAL_PUBLIC -> public [1:0] 377 * |--LITERAL_CLASS -> class [1:7] 378 * |--IDENT -> InputTest [1:13] 379 * `--OBJBLOCK -> OBJBLOCK [1:23] 380 * |--LCURLY -> { [1:23] 381 * |--VARIABLE_DEF -> VARIABLE_DEF [2:4] 382 * | |--MODIFIERS -> MODIFIERS [2:4] 383 * | | `--LITERAL_PRIVATE -> private [2:4] 384 * | |--TYPE -> TYPE [2:12] 385 * | | `--LITERAL_INT -> int [2:12] 386 * | |--IDENT -> wordCount [2:16] 387 * | |--ASSIGN -> = [2:26] 388 * | | `--EXPR -> EXPR [2:28] 389 * | | `--NUM_INT -> 11 [2:28] 390 * | `--SEMI -> ; [2:30] 391 * `--RCURLY -> } [3:0] 392 * </pre> 393 * <p> 394 * The easiest way is to suppress by variable name. As you can see {@code VARIABLE_DEF} 395 * node refers to variable declaration statement and has child node with token type 396 * {@code IDENT} which is used for storing class, method, variable names. 397 * </p> 398 * <p> 399 * The following example demonstrates how variable can be queried by its name: 400 * </p> 401 * <pre> 402 * <suppress-xpath checks="." query="//VARIABLE_DEF[ 403 * ./IDENT[@text='wordCount']]"/> 404 * </pre> 405 * <p> 406 * Another way is to suppress by variable value. Again, if you look at the printed 407 * AST tree above, you will notice that one of the grandchildren of {@code VARIABLE_DEF} 408 * node is responsible for storing variable value -{@code NUM_INT} with value <b>11</b>. 409 * </p> 410 * <p> 411 * The following example demonstrates how variable can be queried by its value, 412 * same approach applies to {@code String, char, float, double, int, long} data types: 413 * </p> 414 * <pre> 415 * <suppress-xpath checks="." query="//VARIABLE_DEF[.//NUM_INT[@text=11]]"/> 416 * </pre> 417 * <p> 418 * Next example is about suppressing method with certain annotation by its name and element value. 419 * </p> 420 * <pre> 421 * public class InputTest { 422 * @Generated("first") // should not be suppressed 423 * public void test1() { 424 * } 425 * 426 * @Generated("second") // should be suppressed 427 * public void test2() { 428 * } 429 * } 430 * </pre> 431 * <p> 432 * First of all we need to look at AST tree printed by our CLI tool: 433 * </p> 434 * <pre> 435 * $ java -jar checkstyle-X.XX-all.jar -t InputTest.java 436 * CLASS_DEF -> CLASS_DEF [1:0] 437 * |--MODIFIERS -> MODIFIERS [1:0] 438 * | `--LITERAL_PUBLIC -> public [1:0] 439 * |--LITERAL_CLASS -> class [1:7] 440 * |--IDENT -> InputTest [1:13] 441 * `--OBJBLOCK -> OBJBLOCK [1:23] 442 * |--LCURLY -> { [1:23] 443 * |--METHOD_DEF -> METHOD_DEF [2:4] 444 * | |--MODIFIERS -> MODIFIERS [2:4] 445 * | | |--ANNOTATION -> ANNOTATION [2:4] 446 * | | | |--AT -> @ [2:4] 447 * | | | |--IDENT -> Generated [2:5] 448 * | | | |--LPAREN -> ( [2:14] 449 * | | | |--EXPR -> EXPR [2:15] 450 * | | | | `--STRING_LITERAL -> "first" [2:15] 451 * | | | `--RPAREN -> ) [2:22] 452 * | | `--LITERAL_PUBLIC -> public [3:4] 453 * | |--TYPE -> TYPE [3:11] 454 * | | `--LITERAL_VOID -> void [3:11] 455 * | |--IDENT -> test1 [3:16] 456 * | |--LPAREN -> ( [3:21] 457 * | |--PARAMETERS -> PARAMETERS [3:22] 458 * | |--RPAREN -> ) [3:22] 459 * | `--SLIST -> { [3:24] 460 * | `--RCURLY -> } [4:4] 461 * |--METHOD_DEF -> METHOD_DEF [6:4] 462 * | |--MODIFIERS -> MODIFIERS [6:4] 463 * | | |--ANNOTATION -> ANNOTATION [6:4] 464 * | | | |--AT -> @ [6:4] 465 * | | | |--IDENT -> Generated [6:5] 466 * | | | |--LPAREN -> ( [6:14] 467 * | | | |--EXPR -> EXPR [6:15] 468 * | | | | `--STRING_LITERAL -> "second" [6:15] 469 * | | | `--RPAREN -> ) [6:23] 470 * | | `--LITERAL_PUBLIC -> public [7:4] 471 * | |--TYPE -> TYPE [7:11] 472 * | | `--LITERAL_VOID -> void [7:11] 473 * | |--IDENT -> test2 [7:16] 474 * | |--LPAREN -> ( [7:21] 475 * | |--PARAMETERS -> PARAMETERS [7:22] 476 * | |--RPAREN -> ) [7:22] 477 * | `--SLIST -> { [7:24] 478 * | `--RCURLY -> } [8:4] 479 * `--RCURLY -> } [9:0] 480 * </pre> 481 * <p> 482 * AST node {@code ANNOTATION -> ANNOTATION [6:4]} has direct child 483 * {@code IDENT -> Generated [6:5]}, therefore can be queried by {@code IDENT} value: 484 * </p> 485 * <pre> 486 * <suppress-xpath checks="." query="//METHOD_DEF[ 487 * .//ANNOTATION/IDENT[@text='Generated']]"/> 488 * </pre> 489 * <p> 490 * The problem with query above that it will suppress violations for all methods 491 * with annotation {@code @Generated}. In order to suppress methods with 492 * {@code @Generated("second")} annotations only, you need to look at AST tree again. 493 * Value of the {@code ANNOTATION} node is stored inside sub-node with token type 494 * {@code STRING_LITERAL}. Use the following query to suppress methods with 495 * {@code @Generated("second")} annotation: 496 * </p> 497 * <pre> 498 * <suppress-xpath checks="." query="//METHOD_DEF[.//ANNOTATION[ 499 * ./IDENT[@text='Generated'] and ./EXPR/STRING_LITERAL[@text='second']]]"/> 500 * </pre> 501 * <p> 502 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} 503 * </p> 504 * 505 * @since 8.6 506 * @noinspection NonFinalFieldReferenceInEquals, NonFinalFieldReferencedInHashCode 507 */ 508public class SuppressionXpathFilter extends AutomaticBean implements 509 TreeWalkerFilter, ExternalResourceHolder { 510 511 /** Specify the location of the <em>suppressions XML document</em> file. */ 512 private String file; 513 /** 514 * Control what to do when the file is not existing. 515 * If optional is set to false the file must exist, or else it ends with error. 516 * On the other hand if optional is true and file is not found, 517 * the filter accepts all audit events. 518 */ 519 private boolean optional; 520 /** Set of individual xpath suppresses. */ 521 private Set<TreeWalkerFilter> filters = new HashSet<>(); 522 523 /** 524 * Setter to specify the location of the <em>suppressions XML document</em> file. 525 * 526 * @param fileName name of the suppressions file. 527 */ 528 public void setFile(String fileName) { 529 file = fileName; 530 } 531 532 /** 533 * Setter to control what to do when the file is not existing. 534 * If optional is set to false the file must exist, or else it ends with error. 535 * On the other hand if optional is true and file is not found, 536 * the filter accepts all audit events. 537 * 538 * @param optional tells if config file existence is optional. 539 */ 540 public void setOptional(boolean optional) { 541 this.optional = optional; 542 } 543 544 @Override 545 public boolean equals(Object obj) { 546 if (this == obj) { 547 return true; 548 } 549 if (obj == null || getClass() != obj.getClass()) { 550 return false; 551 } 552 final SuppressionXpathFilter suppressionXpathFilter = (SuppressionXpathFilter) obj; 553 return Objects.equals(filters, suppressionXpathFilter.filters); 554 } 555 556 @Override 557 public int hashCode() { 558 return Objects.hash(filters); 559 } 560 561 @Override 562 public boolean accept(TreeWalkerAuditEvent treeWalkerAuditEvent) { 563 boolean result = true; 564 for (TreeWalkerFilter filter : filters) { 565 if (!filter.accept(treeWalkerAuditEvent)) { 566 result = false; 567 break; 568 } 569 } 570 return result; 571 } 572 573 @Override 574 public Set<String> getExternalResourceLocations() { 575 return Collections.singleton(file); 576 } 577 578 @Override 579 protected void finishLocalSetup() throws CheckstyleException { 580 if (file != null) { 581 if (optional) { 582 if (FilterUtil.isFileExists(file)) { 583 filters = SuppressionsLoader.loadXpathSuppressions(file); 584 } 585 else { 586 filters = new HashSet<>(); 587 } 588 } 589 else { 590 filters = SuppressionsLoader.loadXpathSuppressions(file); 591 } 592 } 593 } 594 595}