1 /////////////////////////////////////////////////////////////////////////////////////////////// 2 // checkstyle: Checks Java source code and other text files for adherence to a set of rules. 3 // Copyright (C) 2001-2025 the original author or authors. 4 // 5 // This library is free software; you can redistribute it and/or 6 // modify it under the terms of the GNU Lesser General Public 7 // License as published by the Free Software Foundation; either 8 // version 2.1 of the License, or (at your option) any later version. 9 // 10 // This library is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 // Lesser General Public License for more details. 14 // 15 // You should have received a copy of the GNU Lesser General Public 16 // License along with this library; if not, write to the Free Software 17 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 18 /////////////////////////////////////////////////////////////////////////////////////////////// 19 20 package com.puppycrawl.tools.checkstyle.checks.coding; 21 22 import java.util.List; 23 24 import com.puppycrawl.tools.checkstyle.StatelessCheck; 25 import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 26 import com.puppycrawl.tools.checkstyle.api.DetailAST; 27 import com.puppycrawl.tools.checkstyle.utils.CommonUtil; 28 import com.puppycrawl.tools.checkstyle.xpath.AbstractNode; 29 import com.puppycrawl.tools.checkstyle.xpath.RootNode; 30 import net.sf.saxon.Configuration; 31 import net.sf.saxon.om.Item; 32 import net.sf.saxon.sxpath.XPathDynamicContext; 33 import net.sf.saxon.sxpath.XPathEvaluator; 34 import net.sf.saxon.sxpath.XPathExpression; 35 import net.sf.saxon.trans.XPathException; 36 37 /** 38 * <div> 39 * Evaluates Xpath query and report violation on all matching AST nodes. This check allows 40 * user to implement custom checks using Xpath. If Xpath query is not specified explicitly, 41 * then the check does nothing. 42 * </div> 43 * 44 * <p> 45 * It is recommended to define custom message for violation to explain what is not allowed and what 46 * to use instead, default message might be too abstract. To customize a message you need to 47 * add {@code message} element with <b>matchxpath.match</b> as {@code key} attribute and 48 * desired message as {@code value} attribute. 49 * </p> 50 * 51 * <p> 52 * Please read more about Xpath syntax at 53 * <a href="https://www.saxonica.com/html/documentation10/expressions/index.html">Xpath Syntax</a>. 54 * Information regarding Xpath functions can be found at 55 * <a href="https://www.saxonica.com/html/documentation10/functions/fn/index.html"> 56 * XSLT/XPath Reference</a>. 57 * Note, that <b>@text</b> attribute can be used only with token types that are listed in 58 * <a href="https://github.com/checkstyle/checkstyle/search?q=%22TOKEN_TYPES_WITH_TEXT_ATTRIBUTE+%3D+Arrays.asList%22"> 59 * XpathUtil</a>. 60 * </p> 61 * <ul> 62 * <li> 63 * Property {@code query} - Specify Xpath query. 64 * Type is {@code java.lang.String}. 65 * Default value is {@code ""}. 66 * </li> 67 * </ul> 68 * 69 * <p> 70 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} 71 * </p> 72 * 73 * <p> 74 * Violation Message Keys: 75 * </p> 76 * <ul> 77 * <li> 78 * {@code matchxpath.match} 79 * </li> 80 * </ul> 81 * 82 * @since 8.39 83 */ 84 @StatelessCheck 85 public class MatchXpathCheck extends AbstractCheck { 86 87 /** 88 * A key is pointing to the warning message text provided by user. 89 */ 90 public static final String MSG_KEY = "matchxpath.match"; 91 92 /** Specify Xpath query. */ 93 private String query = ""; 94 95 /** Xpath expression. */ 96 private XPathExpression xpathExpression; 97 98 /** 99 * Setter to specify Xpath query. 100 * 101 * @param query Xpath query. 102 * @throws IllegalStateException if creation of xpath expression fails 103 * @since 8.39 104 */ 105 public void setQuery(String query) { 106 this.query = query; 107 if (!query.isEmpty()) { 108 try { 109 final XPathEvaluator xpathEvaluator = 110 new XPathEvaluator(Configuration.newConfiguration()); 111 xpathExpression = xpathEvaluator.createExpression(query); 112 } 113 catch (XPathException exc) { 114 throw new IllegalStateException("Creating Xpath expression failed: " + query, exc); 115 } 116 } 117 } 118 119 @Override 120 public int[] getDefaultTokens() { 121 return getRequiredTokens(); 122 } 123 124 @Override 125 public int[] getAcceptableTokens() { 126 return getRequiredTokens(); 127 } 128 129 @Override 130 public int[] getRequiredTokens() { 131 return CommonUtil.EMPTY_INT_ARRAY; 132 } 133 134 @Override 135 public boolean isCommentNodesRequired() { 136 return true; 137 } 138 139 @Override 140 public void beginTree(DetailAST rootAST) { 141 if (!query.isEmpty()) { 142 final List<DetailAST> matchingNodes = findMatchingNodesByXpathQuery(rootAST); 143 matchingNodes.forEach(node -> log(node, MSG_KEY)); 144 } 145 } 146 147 /** 148 * Find nodes that match query. 149 * 150 * @param rootAST root node 151 * @return list of matching nodes 152 * @throws IllegalStateException if evaluation of xpath query fails 153 */ 154 private List<DetailAST> findMatchingNodesByXpathQuery(DetailAST rootAST) { 155 try { 156 final RootNode rootNode = new RootNode(rootAST); 157 final XPathDynamicContext xpathDynamicContext = 158 xpathExpression.createDynamicContext(rootNode); 159 final List<Item> matchingItems = xpathExpression.evaluate(xpathDynamicContext); 160 return matchingItems.stream() 161 .map(item -> (DetailAST) ((AbstractNode) item).getUnderlyingNode()) 162 .toList(); 163 } 164 catch (XPathException exc) { 165 throw new IllegalStateException("Evaluation of Xpath query failed: " + query, exc); 166 } 167 } 168 }