001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2018 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.api.AbstractCheck; 031import com.puppycrawl.tools.checkstyle.api.DetailAST; 032import com.puppycrawl.tools.checkstyle.api.TokenTypes; 033import com.puppycrawl.tools.checkstyle.utils.TokenUtil; 034 035/** 036 * Checks for multiple occurrences of the same string literal within a 037 * single file. 038 * 039 */ 040@FileStatefulCheck 041public class MultipleStringLiteralsCheck extends AbstractCheck { 042 043 /** 044 * A key is pointing to the warning message text in "messages.properties" 045 * file. 046 */ 047 public static final String MSG_KEY = "multiple.string.literal"; 048 049 /** 050 * The found strings and their positions. 051 * {@code <String, ArrayList>}, with the ArrayList containing StringInfo 052 * objects. 053 */ 054 private final Map<String, List<StringInfo>> stringMap = new HashMap<>(); 055 056 /** 057 * Marks the TokenTypes where duplicate strings should be ignored. 058 */ 059 private final BitSet ignoreOccurrenceContext = new BitSet(); 060 061 /** 062 * The allowed number of string duplicates in a file before an error is 063 * generated. 064 */ 065 private int allowedDuplicates = 1; 066 067 /** 068 * Pattern for matching ignored strings. 069 */ 070 private Pattern ignoreStringsRegexp; 071 072 /** 073 * Construct an instance with default values. 074 */ 075 public MultipleStringLiteralsCheck() { 076 setIgnoreStringsRegexp(Pattern.compile("^\"\"$")); 077 ignoreOccurrenceContext.set(TokenTypes.ANNOTATION); 078 } 079 080 /** 081 * Sets the maximum allowed duplicates of a string. 082 * @param allowedDuplicates The maximum number of duplicates. 083 */ 084 public void setAllowedDuplicates(int allowedDuplicates) { 085 this.allowedDuplicates = allowedDuplicates; 086 } 087 088 /** 089 * Sets regular expression pattern for ignored strings. 090 * @param ignoreStringsRegexp 091 * regular expression pattern for ignored strings 092 * @noinspection WeakerAccess 093 */ 094 public final void setIgnoreStringsRegexp(Pattern ignoreStringsRegexp) { 095 if (ignoreStringsRegexp == null || ignoreStringsRegexp.pattern().isEmpty()) { 096 this.ignoreStringsRegexp = null; 097 } 098 else { 099 this.ignoreStringsRegexp = ignoreStringsRegexp; 100 } 101 } 102 103 /** 104 * Adds a set of tokens the check is interested in. 105 * @param strRep the string representation of the tokens interested in 106 */ 107 public final void setIgnoreOccurrenceContext(String... strRep) { 108 ignoreOccurrenceContext.clear(); 109 for (final String s : strRep) { 110 final int type = TokenUtil.getTokenId(s); 111 ignoreOccurrenceContext.set(type); 112 } 113 } 114 115 @Override 116 public int[] getDefaultTokens() { 117 return getRequiredTokens(); 118 } 119 120 @Override 121 public int[] getAcceptableTokens() { 122 return getRequiredTokens(); 123 } 124 125 @Override 126 public int[] getRequiredTokens() { 127 return new int[] {TokenTypes.STRING_LITERAL}; 128 } 129 130 @Override 131 public void visitToken(DetailAST ast) { 132 if (!isInIgnoreOccurrenceContext(ast)) { 133 final String currentString = ast.getText(); 134 if (ignoreStringsRegexp == null || !ignoreStringsRegexp.matcher(currentString).find()) { 135 List<StringInfo> hitList = stringMap.get(currentString); 136 if (hitList == null) { 137 hitList = new ArrayList<>(); 138 stringMap.put(currentString, hitList); 139 } 140 final int line = ast.getLineNo(); 141 final int col = ast.getColumnNo(); 142 hitList.add(new StringInfo(line, col)); 143 } 144 } 145 } 146 147 /** 148 * Analyses the path from the AST root to a given AST for occurrences 149 * of the token types in {@link #ignoreOccurrenceContext}. 150 * 151 * @param ast the node from where to start searching towards the root node 152 * @return whether the path from the root node to ast contains one of the 153 * token type in {@link #ignoreOccurrenceContext}. 154 */ 155 private boolean isInIgnoreOccurrenceContext(DetailAST ast) { 156 boolean isInIgnoreOccurrenceContext = false; 157 for (DetailAST token = ast; 158 token.getParent() != null; 159 token = token.getParent()) { 160 final int type = token.getType(); 161 if (ignoreOccurrenceContext.get(type)) { 162 isInIgnoreOccurrenceContext = true; 163 break; 164 } 165 } 166 return isInIgnoreOccurrenceContext; 167 } 168 169 @Override 170 public void beginTree(DetailAST rootAST) { 171 stringMap.clear(); 172 } 173 174 @Override 175 public void finishTree(DetailAST rootAST) { 176 for (Map.Entry<String, List<StringInfo>> stringListEntry : stringMap.entrySet()) { 177 final List<StringInfo> hits = stringListEntry.getValue(); 178 if (hits.size() > allowedDuplicates) { 179 final StringInfo firstFinding = hits.get(0); 180 final int line = firstFinding.getLine(); 181 final int col = firstFinding.getCol(); 182 log(line, col, MSG_KEY, stringListEntry.getKey(), hits.size()); 183 } 184 } 185 } 186 187 /** 188 * This class contains information about where a string was found. 189 */ 190 private static final class StringInfo { 191 192 /** 193 * Line of finding. 194 */ 195 private final int line; 196 /** 197 * Column of finding. 198 */ 199 private final int col; 200 201 /** 202 * Creates information about a string position. 203 * @param line int 204 * @param col int 205 */ 206 StringInfo(int line, int col) { 207 this.line = line; 208 this.col = col; 209 } 210 211 /** 212 * The line where a string was found. 213 * @return int Line of the string. 214 */ 215 private int getLine() { 216 return line; 217 } 218 219 /** 220 * The column where a string was found. 221 * @return int Column of the string. 222 */ 223 private int getCol() { 224 return col; 225 } 226 227 } 228 229}