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.checks.annotation;
21  
22  import com.puppycrawl.tools.checkstyle.StatelessCheck;
23  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
24  import com.puppycrawl.tools.checkstyle.api.DetailAST;
25  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
26  import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
27  import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
28  
29  /**
30   * <div>
31   * Checks location of annotation on language elements.
32   * By default, Check enforce to locate annotations before target element,
33   * annotation should be located on separate line from target element.
34   * This check also verifies that the annotations are on the same indenting level
35   * as the annotated element if they are not on the same line.
36   * </div>
37   *
38   * <p>
39   * Attention: Elements that cannot have JavaDoc comments like local variables are not in the
40   * scope of this check even though a token type like {@code VARIABLE_DEF} would match them.
41   * </p>
42   *
43   * <p>
44   * Attention: Annotations among modifiers are ignored (looks like false-negative)
45   * as there might be a problem with annotations for return types:
46   * </p>
47   * <div class="wrapper"><pre class="prettyprint"><code class="language-java">
48   * public @Nullable Long getStartTimeOrNull() { ... }
49   * </code></pre></div>
50   *
51   * <p>
52   * Such annotations are better to keep close to type.
53   * Due to limitations, Checkstyle can not examine the target of an annotation.
54   * </p>
55   *
56   * <p>
57   * Example:
58   * </p>
59   * <div class="wrapper"><pre class="prettyprint"><code class="language-java">
60   * &#64;Override
61   * &#64;Nullable
62   * public String getNameIfPresent() { ... }
63   * </code></pre></div>
64   *
65   * <p>
66   * Notes:
67   * This check does <strong>not</strong> enforce annotations to be placed
68   * immediately after the documentation block. If that behavior is desired, consider also using
69   * <a href="https://checkstyle.org/checks/javadoc/invalidjavadocposition.html#InvalidJavadocPosition">
70   * InvalidJavadocPosition</a>.
71   * </p>
72   *
73   * <p>
74   * The property {@code allowSamelineMultipleAnnotations} has the
75   * dominant effect and allows both single and multiple annotations on
76   * the same line, regardless of whether they are parameterized or parameterless.
77   * </p>
78   *
79   * @since 6.0
80   */
81  @StatelessCheck
82  public class AnnotationLocationCheck extends AbstractCheck {
83  
84      /**
85       * A key is pointing to the warning message text in "messages.properties"
86       * file.
87       */
88      public static final String MSG_KEY_ANNOTATION_LOCATION_ALONE = "annotation.location.alone";
89  
90      /**
91       * A key is pointing to the warning message text in "messages.properties"
92       * file.
93       */
94      public static final String MSG_KEY_ANNOTATION_LOCATION = "annotation.location";
95  
96      /**
97       * Allow single parameterless annotation to be located on the same line as
98       * target element.
99       */
100     private boolean allowSamelineSingleParameterlessAnnotation = true;
101 
102     /**
103      * Allow one and only parameterized annotation to be located on the same line as
104      * target element.
105      */
106     private boolean allowSamelineParameterizedAnnotation;
107 
108     /**
109      * Allow annotation(s) to be located on the same line as
110      * target element.
111      */
112     private boolean allowSamelineMultipleAnnotations;
113 
114     /**
115      * Setter to allow single parameterless annotation to be located on the same line as
116      * target element.
117      *
118      * @param allow User's value of allowSamelineSingleParameterlessAnnotation.
119      * @since 6.1
120      */
121     public final void setAllowSamelineSingleParameterlessAnnotation(boolean allow) {
122         allowSamelineSingleParameterlessAnnotation = allow;
123     }
124 
125     /**
126      * Setter to allow one and only parameterized annotation to be located on the same line as
127      * target element.
128      *
129      * @param allow User's value of allowSamelineParameterizedAnnotation.
130      * @since 6.4
131      */
132     public final void setAllowSamelineParameterizedAnnotation(boolean allow) {
133         allowSamelineParameterizedAnnotation = allow;
134     }
135 
136     /**
137      * Setter to allow annotation(s) to be located on the same line as
138      * target element.
139      *
140      * @param allow User's value of allowSamelineMultipleAnnotations.
141      * @since 6.0
142      */
143     public final void setAllowSamelineMultipleAnnotations(boolean allow) {
144         allowSamelineMultipleAnnotations = allow;
145     }
146 
147     @Override
148     public int[] getDefaultTokens() {
149         return new int[] {
150             TokenTypes.CLASS_DEF,
151             TokenTypes.INTERFACE_DEF,
152             TokenTypes.PACKAGE_DEF,
153             TokenTypes.ENUM_CONSTANT_DEF,
154             TokenTypes.ENUM_DEF,
155             TokenTypes.METHOD_DEF,
156             TokenTypes.CTOR_DEF,
157             TokenTypes.VARIABLE_DEF,
158             TokenTypes.RECORD_DEF,
159             TokenTypes.COMPACT_CTOR_DEF,
160         };
161     }
162 
163     @Override
164     public int[] getAcceptableTokens() {
165         return new int[] {
166             TokenTypes.CLASS_DEF,
167             TokenTypes.INTERFACE_DEF,
168             TokenTypes.PACKAGE_DEF,
169             TokenTypes.ENUM_CONSTANT_DEF,
170             TokenTypes.ENUM_DEF,
171             TokenTypes.METHOD_DEF,
172             TokenTypes.CTOR_DEF,
173             TokenTypes.VARIABLE_DEF,
174             TokenTypes.ANNOTATION_DEF,
175             TokenTypes.ANNOTATION_FIELD_DEF,
176             TokenTypes.RECORD_DEF,
177             TokenTypes.COMPACT_CTOR_DEF,
178         };
179     }
180 
181     @Override
182     public int[] getRequiredTokens() {
183         return CommonUtil.EMPTY_INT_ARRAY;
184     }
185 
186     @Override
187     public void visitToken(DetailAST ast) {
188         // ignore variable def tokens that are not field definitions
189         if (ast.getType() != TokenTypes.VARIABLE_DEF
190                 || ast.getParent().getType() == TokenTypes.OBJBLOCK
191                 || ast.getParent().getType() == TokenTypes.COMPACT_COMPILATION_UNIT) {
192             DetailAST node = ast.findFirstToken(TokenTypes.MODIFIERS);
193             if (node == null) {
194                 node = ast.findFirstToken(TokenTypes.ANNOTATIONS);
195             }
196             checkAnnotations(node, getExpectedAnnotationIndentation(node));
197         }
198     }
199 
200     /**
201      * Returns an expected annotation indentation.
202      * The expected indentation should be the same as the indentation of the target node.
203      *
204      * @param node modifiers or annotations node.
205      * @return the annotation indentation.
206      */
207     private static int getExpectedAnnotationIndentation(DetailAST node) {
208         return node.getColumnNo();
209     }
210 
211     /**
212      * Checks annotations positions in code:
213      * 1) Checks whether the annotations locations are correct.
214      * 2) Checks whether the annotations have the valid indentation level.
215      *
216      * @param modifierNode modifiers node.
217      * @param correctIndentation correct indentation of the annotation.
218      */
219     private void checkAnnotations(DetailAST modifierNode, int correctIndentation) {
220         DetailAST annotation = modifierNode.getFirstChild();
221 
222         while (annotation != null && annotation.getType() == TokenTypes.ANNOTATION) {
223             final boolean hasParameters = isParameterized(annotation);
224 
225             if (!isCorrectLocation(annotation, hasParameters)) {
226                 log(annotation,
227                         MSG_KEY_ANNOTATION_LOCATION_ALONE, getAnnotationName(annotation));
228             }
229             else if (annotation.getColumnNo() != correctIndentation && !hasNodeBefore(annotation)) {
230                 log(annotation, MSG_KEY_ANNOTATION_LOCATION,
231                     getAnnotationName(annotation), annotation.getColumnNo(), correctIndentation);
232             }
233             annotation = annotation.getNextSibling();
234         }
235     }
236 
237     /**
238      * Checks whether an annotation has parameters.
239      *
240      * @param annotation annotation node.
241      * @return true if the annotation has parameters.
242      */
243     private static boolean isParameterized(DetailAST annotation) {
244         return TokenUtil.findFirstTokenByPredicate(annotation, ast -> {
245             return ast.getType() == TokenTypes.EXPR
246                 || ast.getType() == TokenTypes.ANNOTATION_MEMBER_VALUE_PAIR;
247         }).isPresent();
248     }
249 
250     /**
251      * Returns the name of the given annotation.
252      *
253      * @param annotation annotation node.
254      * @return annotation name.
255      */
256     private static String getAnnotationName(DetailAST annotation) {
257         DetailAST identNode = annotation.findFirstToken(TokenTypes.IDENT);
258         if (identNode == null) {
259             identNode = annotation.findFirstToken(TokenTypes.DOT).findFirstToken(TokenTypes.IDENT);
260         }
261         return identNode.getText();
262     }
263 
264     /**
265      * Checks whether an annotation has a correct location.
266      * Annotation location is considered correct
267      * if {@link AnnotationLocationCheck#allowSamelineMultipleAnnotations} is set to true.
268      * The method also:
269      * 1) checks parameterized annotation location considering
270      * the value of {@link AnnotationLocationCheck#allowSamelineParameterizedAnnotation};
271      * 2) checks parameterless annotation location considering
272      * the value of {@link AnnotationLocationCheck#allowSamelineSingleParameterlessAnnotation};
273      * 3) checks annotation location;
274      *
275      * @param annotation annotation node.
276      * @param hasParams whether an annotation has parameters.
277      * @return true if the annotation has a correct location.
278      */
279     private boolean isCorrectLocation(DetailAST annotation, boolean hasParams) {
280         final boolean allowingCondition;
281 
282         if (hasParams) {
283             allowingCondition = allowSamelineParameterizedAnnotation;
284         }
285         else {
286             allowingCondition = allowSamelineSingleParameterlessAnnotation;
287         }
288         return allowSamelineMultipleAnnotations
289             || allowingCondition && !hasNodeBefore(annotation)
290             || !hasNodeBeside(annotation);
291     }
292 
293     /**
294      * Checks whether an annotation node has any node before on the same line.
295      *
296      * @param annotation annotation node.
297      * @return true if an annotation node has any node before on the same line.
298      */
299     private static boolean hasNodeBefore(DetailAST annotation) {
300         final int annotationLineNo = annotation.getLineNo();
301         final DetailAST previousNode = annotation.getPreviousSibling();
302 
303         return previousNode != null && annotationLineNo == previousNode.getLineNo();
304     }
305 
306     /**
307      * Checks whether an annotation node has any node before or after on the same line.
308      *
309      * @param annotation annotation node.
310      * @return true if an annotation node has any node before or after on the same line.
311      */
312     private static boolean hasNodeBeside(DetailAST annotation) {
313         return hasNodeBefore(annotation) || hasNodeAfter(annotation);
314     }
315 
316     /**
317      * Checks whether an annotation node has any node after on the same line.
318      *
319      * @param annotation annotation node.
320      * @return true if an annotation node has any node after on the same line.
321      */
322     private static boolean hasNodeAfter(DetailAST annotation) {
323         final int annotationLineNo = annotation.getLineNo();
324         DetailAST nextNode = annotation.getNextSibling();
325 
326         if (nextNode == null) {
327             nextNode = annotation.getParent().getNextSibling();
328         }
329 
330         return annotationLineNo == nextNode.getLineNo();
331     }
332 
333 }