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