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 java.util.Objects;
23  import java.util.Optional;
24  import java.util.regex.Pattern;
25  import java.util.stream.Stream;
26  
27  import com.puppycrawl.tools.checkstyle.StatelessCheck;
28  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
29  import com.puppycrawl.tools.checkstyle.api.DetailAST;
30  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
31  import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTagInfo;
32  import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil;
33  import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
34  import com.puppycrawl.tools.checkstyle.utils.JavadocUtil;
35  
36  /**
37   * <div>
38   * Verifies that the {@code @Override} annotation is present
39   * when the {@code @inheritDoc} javadoc tag is present.
40   * </div>
41   *
42   * <p>
43   * Rationale: The &#64;Override annotation helps
44   * compiler tools ensure that an override is actually occurring.  It is
45   * quite easy to accidentally overload a method or hide a static method
46   * and using the &#64;Override annotation points out these problems.
47   * </p>
48   *
49   * <p>
50   * This check will log a violation if using the &#64;inheritDoc tag on a method that
51   * is not valid (ex: private, or static method).
52   * </p>
53   *
54   * <p>
55   * There is a slight difference between the &#64;Override annotation in Java 5 versus
56   * Java 6 and above. In Java 5, any method overridden from an interface cannot
57   * be annotated with &#64;Override. In Java 6 this behavior is allowed.
58   * </p>
59   *
60   * <p>
61   * As a result of the aforementioned difference between Java 5 and Java 6, a
62   * property called {@code javaFiveCompatibility} is available. This
63   * property will only check classes, interfaces, etc. that do not contain the
64   * extends or implements keyword or are not anonymous classes. This means it
65   * only checks methods overridden from {@code java.lang.Object}.
66   * <b>Java 5 Compatibility mode severely limits this check. It is recommended to
67   * only use it on Java 5 source.</b>
68   * </p>
69   *
70   * @since 5.0
71   */
72  @StatelessCheck
73  public final class MissingOverrideCheck extends AbstractCheck {
74  
75      /**
76       * A key is pointing to the warning message text in "messages.properties"
77       * file.
78       */
79      public static final String MSG_KEY_TAG_NOT_VALID_ON = "tag.not.valid.on";
80  
81      /**
82       * A key is pointing to the warning message text in "messages.properties"
83       * file.
84       */
85      public static final String MSG_KEY_ANNOTATION_MISSING_OVERRIDE =
86          "annotation.missing.override";
87  
88      /** Compiled regexp to match Javadoc tags with no argument and {}. */
89      private static final Pattern MATCH_INHERIT_DOC =
90              CommonUtil.createPattern("\\{\\s*@(inheritDoc)\\s*\\}");
91  
92      /**
93       * Enable java 5 compatibility mode.
94       */
95      private boolean javaFiveCompatibility;
96  
97      /**
98       * Creates a new {@code MissingOverrideCheck} instance.
99       */
100     public MissingOverrideCheck() {
101         // no code by default
102     }
103 
104     /**
105      * Setter to enable java 5 compatibility mode.
106      *
107      * @param compatibility compatibility or not
108      * @since 5.0
109      */
110     public void setJavaFiveCompatibility(final boolean compatibility) {
111         javaFiveCompatibility = compatibility;
112     }
113 
114     @Override
115     public int[] getDefaultTokens() {
116         return getRequiredTokens();
117     }
118 
119     @Override
120     public int[] getAcceptableTokens() {
121         return getRequiredTokens();
122     }
123 
124     @Override
125     public boolean isCommentNodesRequired() {
126         return true;
127     }
128 
129     @Override
130     public int[] getRequiredTokens() {
131         return new int[]
132         {TokenTypes.METHOD_DEF, };
133     }
134 
135     @Override
136     public void visitToken(final DetailAST ast) {
137         final boolean containsTag = containsInheritDocTag(ast);
138         if (containsTag && !JavadocTagInfo.INHERIT_DOC.isValidOn(ast)) {
139             log(ast, MSG_KEY_TAG_NOT_VALID_ON,
140                 JavadocTagInfo.INHERIT_DOC.getText());
141         }
142         else if (containsTag
143                 && !AnnotationUtil.hasOverrideAnnotation(ast)
144                 && (!javaFiveCompatibility || doesOverrideOnlyObjectMethods(ast))) {
145             log(ast, MSG_KEY_ANNOTATION_MISSING_OVERRIDE);
146         }
147     }
148 
149     /**
150      * Checks whether the method's enclosing type can only be overriding methods
151      * declared in {@code java.lang.Object}. This is the case when the enclosing type
152      * does not extend or implement anything and is not an anonymous class. A top-level
153      * method in a compact source file has no enclosing type node ({@code defOrNew} is
154      * null); its implicit class satisfies this condition as well.
155      *
156      * @param ast method AST node
157      * @return true if the method's enclosing type can only override
158      *     {@code java.lang.Object} methods
159      */
160     private static boolean doesOverrideOnlyObjectMethods(DetailAST ast) {
161         final DetailAST defOrNew = ast.getParent().getParent();
162         return defOrNew == null
163             || defOrNew.findFirstToken(TokenTypes.EXTENDS_CLAUSE) == null
164                 && defOrNew.findFirstToken(TokenTypes.IMPLEMENTS_CLAUSE) == null
165                 && defOrNew.getType() != TokenTypes.LITERAL_NEW;
166     }
167 
168     /**
169      * Checks to see if the ast contains a inheritDoc tag.
170      *
171      * @param ast method AST node
172      * @return true if contains the tag
173      */
174     private static boolean containsInheritDocTag(DetailAST ast) {
175         final DetailAST modifiers = ast.getFirstChild();
176         final DetailAST startNode;
177         if (modifiers.hasChildren()) {
178             startNode = Optional.ofNullable(ast.getFirstChild()
179                     .findFirstToken(TokenTypes.ANNOTATION))
180                 .orElse(modifiers);
181         }
182         else {
183             startNode = ast.findFirstToken(TokenTypes.TYPE);
184         }
185         final Optional<String> javadoc =
186             Stream.iterate(startNode.getLastChild(), Objects::nonNull,
187                     DetailAST::getPreviousSibling)
188             .filter(node -> node.getType() == TokenTypes.BLOCK_COMMENT_BEGIN)
189             .map(DetailAST::getFirstChild)
190             .map(DetailAST::getText)
191             .filter(JavadocUtil::isJavadocComment)
192             .findFirst();
193         return javadoc.isPresent()
194                 && MATCH_INHERIT_DOC.matcher(javadoc.orElseThrow()).find();
195     }
196 
197 }