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.coding; 021 022import java.util.ArrayList; 023import java.util.BitSet; 024import java.util.HashMap; 025import java.util.List; 026import java.util.Map; 027import java.util.regex.Pattern; 028 029import com.puppycrawl.tools.checkstyle.FileStatefulCheck; 030import com.puppycrawl.tools.checkstyle.PropertyType; 031import com.puppycrawl.tools.checkstyle.XdocsPropertyType; 032import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 033import com.puppycrawl.tools.checkstyle.api.DetailAST; 034import com.puppycrawl.tools.checkstyle.api.TokenTypes; 035import com.puppycrawl.tools.checkstyle.utils.CheckUtil; 036import com.puppycrawl.tools.checkstyle.utils.TokenUtil; 037 038/** 039 * <p> 040 * Checks for multiple occurrences of the same string literal within a single file. 041 * </p> 042 * <p> 043 * Rationale: Code duplication makes maintenance more difficult, so it can be better 044 * to replace the multiple occurrences with a constant. 045 * </p> 046 * <ul> 047 * <li> 048 * Property {@code allowedDuplicates} - Specify the maximum number of occurrences 049 * to allow without generating a warning. 050 * Type is {@code int}. 051 * Default value is {@code 1}. 052 * </li> 053 * <li> 054 * Property {@code ignoreOccurrenceContext} - Specify token type names where duplicate 055 * strings are ignored even if they don't match ignoredStringsRegexp. This allows you to 056 * exclude syntactical contexts like annotations or static initializers from the check. 057 * Type is {@code java.lang.String[]}. 058 * Validation type is {@code tokenTypesSet}. 059 * Default value is {@code ANNOTATION}. 060 * </li> 061 * <li> 062 * Property {@code ignoreStringsRegexp} - Specify RegExp for ignored strings (with quotation marks). 063 * Type is {@code java.util.regex.Pattern}. 064 * Default value is {@code "^""$"}. 065 * </li> 066 * </ul> 067 * <p> 068 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} 069 * </p> 070 * <p> 071 * Violation Message Keys: 072 * </p> 073 * <ul> 074 * <li> 075 * {@code multiple.string.literal} 076 * </li> 077 * </ul> 078 * 079 * @since 3.5 080 */ 081@FileStatefulCheck 082public class MultipleStringLiteralsCheck extends AbstractCheck { 083 084 /** 085 * A key is pointing to the warning message text in "messages.properties" 086 * file. 087 */ 088 public static final String MSG_KEY = "multiple.string.literal"; 089 090 /** 091 * Compiled pattern for all system newlines. 092 */ 093 private static final Pattern ALL_NEW_LINES = Pattern.compile("\\R"); 094 095 /** 096 * String used to amend TEXT_BLOCK_CONTENT so that it matches STRING_LITERAL. 097 */ 098 private static final String QUOTE = "\""; 099 100 /** 101 * The found strings and their tokens. 102 */ 103 private final Map<String, List<DetailAST>> stringMap = new HashMap<>(); 104 105 /** 106 * Specify token type names where duplicate strings are ignored even if they 107 * don't match ignoredStringsRegexp. This allows you to exclude syntactical 108 * contexts like annotations or static initializers from the check. 109 */ 110 @XdocsPropertyType(PropertyType.TOKEN_ARRAY) 111 private final BitSet ignoreOccurrenceContext = new BitSet(); 112 113 /** 114 * Specify the maximum number of occurrences to allow without generating a warning. 115 */ 116 private int allowedDuplicates = 1; 117 118 /** 119 * Specify RegExp for ignored strings (with quotation marks). 120 */ 121 private Pattern ignoreStringsRegexp; 122 123 /** 124 * Construct an instance with default values. 125 */ 126 public MultipleStringLiteralsCheck() { 127 setIgnoreStringsRegexp(Pattern.compile("^\"\"$")); 128 ignoreOccurrenceContext.set(TokenTypes.ANNOTATION); 129 } 130 131 /** 132 * Setter to specify the maximum number of occurrences to allow without generating a warning. 133 * 134 * @param allowedDuplicates The maximum number of duplicates. 135 * @since 3.5 136 */ 137 public void setAllowedDuplicates(int allowedDuplicates) { 138 this.allowedDuplicates = allowedDuplicates; 139 } 140 141 /** 142 * Setter to specify RegExp for ignored strings (with quotation marks). 143 * 144 * @param ignoreStringsRegexp 145 * regular expression pattern for ignored strings 146 * @noinspection WeakerAccess 147 * @noinspectionreason WeakerAccess - we avoid 'protected' when possible 148 * @since 4.0 149 */ 150 public final void setIgnoreStringsRegexp(Pattern ignoreStringsRegexp) { 151 if (ignoreStringsRegexp == null || ignoreStringsRegexp.pattern().isEmpty()) { 152 this.ignoreStringsRegexp = null; 153 } 154 else { 155 this.ignoreStringsRegexp = ignoreStringsRegexp; 156 } 157 } 158 159 /** 160 * Setter to specify token type names where duplicate strings are ignored even 161 * if they don't match ignoredStringsRegexp. This allows you to exclude 162 * syntactical contexts like annotations or static initializers from the check. 163 * 164 * @param strRep the string representation of the tokens interested in 165 * @since 4.4 166 */ 167 public final void setIgnoreOccurrenceContext(String... strRep) { 168 ignoreOccurrenceContext.clear(); 169 for (final String s : strRep) { 170 final int type = TokenUtil.getTokenId(s); 171 ignoreOccurrenceContext.set(type); 172 } 173 } 174 175 @Override 176 public int[] getDefaultTokens() { 177 return getRequiredTokens(); 178 } 179 180 @Override 181 public int[] getAcceptableTokens() { 182 return getRequiredTokens(); 183 } 184 185 @Override 186 public int[] getRequiredTokens() { 187 return new int[] { 188 TokenTypes.STRING_LITERAL, 189 TokenTypes.TEXT_BLOCK_CONTENT, 190 }; 191 } 192 193 @Override 194 public void visitToken(DetailAST ast) { 195 if (!isInIgnoreOccurrenceContext(ast)) { 196 final String currentString; 197 if (ast.getType() == TokenTypes.TEXT_BLOCK_CONTENT) { 198 final String strippedString = 199 CheckUtil.stripIndentAndInitialNewLineFromTextBlock(ast.getText()); 200 // We need to add quotes here to be consistent with STRING_LITERAL text. 201 currentString = QUOTE + strippedString + QUOTE; 202 } 203 else { 204 currentString = ast.getText(); 205 } 206 if (ignoreStringsRegexp == null 207 || !ignoreStringsRegexp.matcher(currentString).find()) { 208 stringMap.computeIfAbsent(currentString, key -> new ArrayList<>()).add(ast); 209 } 210 } 211 } 212 213 /** 214 * Analyses the path from the AST root to a given AST for occurrences 215 * of the token types in {@link #ignoreOccurrenceContext}. 216 * 217 * @param ast the node from where to start searching towards the root node 218 * @return whether the path from the root node to ast contains one of the 219 * token type in {@link #ignoreOccurrenceContext}. 220 */ 221 private boolean isInIgnoreOccurrenceContext(DetailAST ast) { 222 boolean isInIgnoreOccurrenceContext = false; 223 for (DetailAST token = ast; token != null; token = token.getParent()) { 224 final int type = token.getType(); 225 if (ignoreOccurrenceContext.get(type)) { 226 isInIgnoreOccurrenceContext = true; 227 break; 228 } 229 } 230 return isInIgnoreOccurrenceContext; 231 } 232 233 @Override 234 public void beginTree(DetailAST rootAST) { 235 stringMap.clear(); 236 } 237 238 @Override 239 public void finishTree(DetailAST rootAST) { 240 for (Map.Entry<String, List<DetailAST>> stringListEntry : stringMap.entrySet()) { 241 final List<DetailAST> hits = stringListEntry.getValue(); 242 if (hits.size() > allowedDuplicates) { 243 final DetailAST firstFinding = hits.get(0); 244 final String recurringString = 245 ALL_NEW_LINES.matcher( 246 stringListEntry.getKey()).replaceAll("\\\\n"); 247 log(firstFinding, MSG_KEY, recurringString, hits.size()); 248 } 249 } 250 } 251} 252