View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2026 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.api;
21  
22  import java.util.Collections;
23  import java.util.HashSet;
24  import java.util.Set;
25  import java.util.SortedSet;
26  import java.util.TreeSet;
27  
28  /**
29   * The base class for checks.
30   *
31   * @see <a href="{@docRoot}/../writing-checks.html" target="_top">Writing your own checks</a>
32   * @noinspection NoopMethodInAbstractClass
33   * @noinspectionreason NoopMethodInAbstractClass - we allow each check to
34   *      define these methods, as needed. They should be overridden only by demand in subclasses
35   */
36  public abstract class AbstractCheck extends AbstractViolationReporter {
37  
38      /**
39       * The check context.
40       *
41       * @noinspection ThreadLocalNotStaticFinal
42       * @noinspectionreason ThreadLocalNotStaticFinal - static context
43       *      is problematic for multithreading
44       */
45      private final ThreadLocal<FileContext> context = ThreadLocal.withInitial(FileContext::new);
46  
47      /** The tokens the check is interested in. */
48      private final Set<String> tokens = new HashSet<>();
49  
50      /**
51       * The tab width for column reporting. Default is uninitialized as the value is inherited from
52       * the parent module.
53       */
54      private int tabWidth;
55  
56      /**
57       * Creates a new {@code AbstractCheck} instance.
58       */
59      protected AbstractCheck() {
60          // no code by default
61      }
62  
63      /**
64       * Returns the default token a check is interested in. Only used if the
65       * configuration for a check does not define the tokens.
66       *
67       * @return the default tokens
68       * @see TokenTypes
69       */
70      public abstract int[] getDefaultTokens();
71  
72      /**
73       * The configurable token set.
74       * Used to protect Checks against malicious users who specify an
75       * unacceptable token set in the configuration file.
76       * The default implementation returns the check's default tokens.
77       *
78       * @return the token set this check is designed for.
79       * @see TokenTypes
80       */
81      public abstract int[] getAcceptableTokens();
82  
83      /**
84       * The tokens that this check must be registered for.
85       *
86       * @return the token set this must be registered for.
87       * @see TokenTypes
88       */
89      public abstract int[] getRequiredTokens();
90  
91      /**
92       * Whether comment nodes are required or not.
93       *
94       * @return false as a default value.
95       */
96      public boolean isCommentNodesRequired() {
97          return false;
98      }
99  
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 }