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.api;
021
022import java.util.Collections;
023import java.util.HashSet;
024import java.util.Set;
025import java.util.SortedSet;
026import java.util.TreeSet;
027
028/**
029 * The base class for checks.
030 *
031 * @see <a href="{@docRoot}/../writing-checks.html" target="_top">Writing your own checks</a>
032 * @noinspection NoopMethodInAbstractClass
033 * @noinspectionreason NoopMethodInAbstractClass - we allow each check to
034 *      define these methods, as needed. They should be overridden only by demand in subclasses
035 */
036public abstract class AbstractCheck extends AbstractViolationReporter {
037
038    /**
039     * The check context.
040     *
041     * @noinspection ThreadLocalNotStaticFinal
042     * @noinspectionreason ThreadLocalNotStaticFinal - static context
043     *      is problematic for multithreading
044     */
045    private final ThreadLocal<FileContext> context = ThreadLocal.withInitial(FileContext::new);
046
047    /** The tokens the check is interested in. */
048    private final Set<String> tokens = new HashSet<>();
049
050    /**
051     * The tab width for column reporting. Default is uninitialized as the value is inherited from
052     * the parent module.
053     */
054    private int tabWidth;
055
056    /**
057     * Creates a new {@code AbstractCheck} instance.
058     */
059    protected AbstractCheck() {
060        // no code by default
061    }
062
063    /**
064     * Returns the default token a check is interested in. Only used if the
065     * configuration for a check does not define the tokens.
066     *
067     * @return the default tokens
068     * @see TokenTypes
069     */
070    public abstract int[] getDefaultTokens();
071
072    /**
073     * The configurable token set.
074     * Used to protect Checks against malicious users who specify an
075     * unacceptable token set in the configuration file.
076     * The default implementation returns the check's default tokens.
077     *
078     * @return the token set this check is designed for.
079     * @see TokenTypes
080     */
081    public abstract int[] getAcceptableTokens();
082
083    /**
084     * The tokens that this check must be registered for.
085     *
086     * @return the token set this must be registered for.
087     * @see TokenTypes
088     */
089    public abstract int[] getRequiredTokens();
090
091    /**
092     * Whether comment nodes are required or not.
093     *
094     * @return false as a default value.
095     */
096    public boolean isCommentNodesRequired() {
097        return false;
098    }
099
100    /**
101     * Adds a set of tokens the check is interested in.
102     *
103     * @param strRep the string representation of the tokens interested in
104     * @noinspection WeakerAccess
105     * @noinspectionreason WeakerAccess - we avoid 'protected' when possible
106     */
107    public final void setTokens(String... strRep) {
108        Collections.addAll(tokens, strRep);
109    }
110
111    /**
112     * Returns the tokens registered for the check.
113     *
114     * @return the set of token names
115     */
116    public final Set<String> getTokenNames() {
117        return Collections.unmodifiableSet(tokens);
118    }
119
120    /**
121     * Returns the sorted set of {@link Violation}.
122     *
123     * @return the sorted set of {@code Violation}.
124     */
125    public SortedSet<Violation> getViolations() {
126        return new TreeSet<>(context.get().violations);
127    }
128
129    /**
130     * Clears the sorted set of {@link Violation} of the check.
131     */
132    public final void clearViolations() {
133        context.get().violations.clear();
134    }
135
136    /**
137     * Initialize the check. This is the time to verify that the check has
138     * everything required to perform its job.
139     */
140    public void init() {
141        // No code by default, should be overridden only by demand at subclasses
142    }
143
144    /**
145     * Destroy the check. It is being retired from service.
146     */
147    public void destroy() {
148        context.remove();
149    }
150
151    /**
152     * Called before the starting to process a tree. Ideal place to initialize
153     * information that is to be collected whilst processing a tree.
154     *
155     * @param rootAST the root of the tree
156     */
157    public void beginTree(DetailAST rootAST) {
158        // No code by default, should be overridden only by demand at subclasses
159    }
160
161    /**
162     * Called after finished processing a tree. Ideal place to report on
163     * information collected whilst processing a tree.
164     *
165     * @param rootAST the root of the tree
166     */
167    public void finishTree(DetailAST rootAST) {
168        // No code by default, should be overridden only by demand at subclasses
169    }
170
171    /**
172     * Called to process a token.
173     *
174     * @param ast the token to process
175     */
176    public void visitToken(DetailAST ast) {
177        // No code by default, should be overridden only by demand at subclasses
178    }
179
180    /**
181     * Called after all the child nodes have been process.
182     *
183     * @param ast the token leaving
184     */
185    public void leaveToken(DetailAST ast) {
186        // No code by default, should be overridden only by demand at subclasses
187    }
188
189    /**
190     * Set the file contents associated with the tree.
191     *
192     * @param contents the manager
193     */
194    public final void setFileContents(FileContents contents) {
195        context.get().fileContents = contents;
196    }
197
198    /**
199     * Returns the file contents associated with the tree.
200     *
201     * @return the file contents
202     * @deprecated
203     *      Usage of this method is no longer accepted.
204     *      Please use AST based methods instead.
205     * @noinspection WeakerAccess
206     * @noinspectionreason WeakerAccess - we avoid 'protected' when possible
207     */
208    @Deprecated(since = "9.3")
209    public final FileContents getFileContents() {
210        return context.get().fileContents;
211    }
212
213    /**
214     * Get tab width to report audit events with.
215     *
216     * @return the tab width to audit events with
217     */
218    protected final int getTabWidth() {
219        return tabWidth;
220    }
221
222    /**
223     * Set the tab width to report audit events with.
224     *
225     * @param tabWidth an {@code int} value
226     */
227    public final void setTabWidth(int tabWidth) {
228        this.tabWidth = tabWidth;
229    }
230
231    @Override
232    public final void log(int line, String key, Object... args) {
233        context.get().violations.add(
234            new Violation(
235                line,
236                getMessageBundle(),
237                key,
238                args,
239                getSeverityLevel(),
240                getId(),
241                getClass(),
242                getCustomMessages().get(key)));
243    }
244
245    /**
246     * Helper method to log a Violation.
247     *
248     * @param ast a node to get line id column numbers associated with the violation
249     * @param key key to locale violation format
250     * @param args arguments to format
251     */
252    public final void log(DetailAST ast, String key, Object... args) {
253        // ApiUtil.lengthExpandedTabs returns column number considering tabulation
254        // characters, it takes line from the file by line number, ast column number and tab
255        // width as arguments. Returned value is 0-based, but user must see column number starting
256        // from 1, that is why result of the method ApiUtil.lengthExpandedTabs
257        // is increased by one.
258
259        final int col = 1 + ApiUtil.lengthExpandedTabs(
260                getLines()[ast.getLineNo() - 1], ast.getColumnNo(), tabWidth);
261        context.get().violations.add(
262                new Violation(
263                        ast.getLineNo(),
264                        col,
265                        ast.getColumnNo(),
266                        ast.getType(),
267                        getMessageBundle(),
268                        key,
269                        args,
270                        getSeverityLevel(),
271                        getId(),
272                        getClass(),
273                        getCustomMessages().get(key)));
274    }
275
276    @Override
277    public final void log(int lineNo, int colNo, String key,
278            Object... args) {
279        final int col = 1 + ApiUtil.lengthExpandedTabs(
280            getLines()[lineNo - 1], colNo, tabWidth);
281        context.get().violations.add(
282            new Violation(
283                lineNo,
284                col,
285                getMessageBundle(),
286                key,
287                args,
288                getSeverityLevel(),
289                getId(),
290                getClass(),
291                getCustomMessages().get(key)));
292    }
293
294    /**
295     * Returns the lines associated with the tree.
296     *
297     * @return the file contents
298     */
299    public final String[] getLines() {
300        return context.get().fileContents.getLines();
301    }
302
303    /**
304     * Returns the line associated with the tree.
305     *
306     * @param index index of the line
307     * @return the line from the file contents
308     */
309    public final String getLine(int index) {
310        return context.get().fileContents.getLine(index);
311    }
312
313    /**
314     * Returns full path to the file.
315     *
316     * @return full path to file.
317     */
318    public final String getFilePath() {
319        return context.get().fileContents.getFileName();
320    }
321
322    /**
323     * Returns code point representation of file text from given line number.
324     *
325     * @param index index of the line
326     * @return the array of Unicode code points
327     */
328    public final int[] getLineCodePoints(int index) {
329        return getLine(index).codePoints().toArray();
330    }
331
332    /**
333     * The actual context holder.
334     */
335    private static final class FileContext {
336
337        /** The sorted set for collecting violations. */
338        private final SortedSet<Violation> violations = new TreeSet<>();
339
340        /** The current file contents. */
341        private FileContents fileContents;
342
343        /**
344         * Creates a new {@code FileContext} instance.
345         */
346        private FileContext() {
347            // no code by default
348        }
349
350    }
351
352}