001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2020 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.annotation;
021
022import java.util.Arrays;
023import java.util.HashSet;
024import java.util.Set;
025
026import com.puppycrawl.tools.checkstyle.StatelessCheck;
027import com.puppycrawl.tools.checkstyle.api.DetailAST;
028import com.puppycrawl.tools.checkstyle.api.DetailNode;
029import com.puppycrawl.tools.checkstyle.api.JavadocTokenTypes;
030import com.puppycrawl.tools.checkstyle.api.TokenTypes;
031import com.puppycrawl.tools.checkstyle.checks.javadoc.AbstractJavadocCheck;
032import com.puppycrawl.tools.checkstyle.checks.javadoc.JavadocTagInfo;
033import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil;
034
035/**
036 * <p>
037 * Verifies that the annotation {@code @Deprecated} and the Javadoc tag
038 * {@code @deprecated} are both present when either of them is present.
039 * </p>
040 * <p>
041 * Both ways of flagging deprecation serve their own purpose.
042 * The &#64;Deprecated annotation is used for compilers and development tools.
043 * The &#64;deprecated javadoc tag is used to document why something is deprecated
044 * and what, if any, alternatives exist.
045 * </p>
046 * <p>
047 * In order to properly mark something as deprecated both forms of
048 * deprecation should be present.
049 * </p>
050 * <p>
051 * Package deprecation is a exception to the rule of always using the
052 * javadoc tag and annotation to deprecate.  It is not clear if the javadoc
053 * tool will support it or not as newer versions keep flip flopping on if
054 * it is supported or will cause an error. See
055 * <a href="https://bugs.openjdk.java.net/browse/JDK-8160601">JDK-8160601</a>.
056 * The deprecated javadoc tag is currently the only way to say why the package
057 * is deprecated and what to use instead.  Until this is resolved, if you don't
058 * want to print violations on package-info, you can use a
059 * <a href="https://checkstyle.org/config_filters.html">filter</a> to ignore
060 * these files until the javadoc tool faithfully supports it. An example config
061 * using SuppressionSingleFilter is:
062 * </p>
063 * <pre>
064 * &lt;!-- required till https://bugs.openjdk.java.net/browse/JDK-8160601 --&gt;
065 * &lt;module name="SuppressionSingleFilter"&gt;
066 *     &lt;property name="checks" value="MissingDeprecatedCheck"/&gt;
067 *     &lt;property name="files" value="package-info\.java"/&gt;
068 * &lt;/module&gt;
069 * </pre>
070 * <ul>
071 * <li>
072 * Property {@code violateExecutionOnNonTightHtml} - Control when to
073 * print violations if the Javadoc being examined by this check violates the
074 * tight html rules defined at
075 * <a href="https://checkstyle.org/writingjavadocchecks.html#Tight-HTML_rules">
076 * Tight-HTML Rules</a>.
077 * Type is {@code boolean}.
078 * Default value is {@code false}.
079 * </li>
080 * </ul>
081 * <p>
082 * To configure the check:
083 * </p>
084 * <pre>
085 * &lt;module name=&quot;MissingDeprecated&quot;/&gt;
086 * </pre>
087 * <p>
088 * Examples of validating source code:
089 * </p>
090 * <pre>
091 * &#64;Deprecated
092 * public static final int MY_CONST = 123456; // no violation
093 *
094 * &#47;** This javadoc is missing deprecated tag. *&#47;
095 * &#64;Deprecated
096 * public static final int COUNTER = 10; // violation
097 * </pre>
098 * <p>
099 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
100 * </p>
101 * <p>
102 * Violation Message Keys:
103 * </p>
104 * <ul>
105 * <li>
106 * {@code annotation.missing.deprecated}
107 * </li>
108 * <li>
109 * {@code javadoc.duplicateTag}
110 * </li>
111 * <li>
112 * {@code javadoc.missed.html.close}
113 * </li>
114 * <li>
115 * {@code javadoc.parse.rule.error}
116 * </li>
117 * <li>
118 * {@code javadoc.wrong.singleton.html.tag}
119 * </li>
120 * </ul>
121 *
122 * @since 5.0
123 */
124@StatelessCheck
125public final class MissingDeprecatedCheck extends AbstractJavadocCheck {
126
127    /**
128     * A key is pointing to the warning message text in "messages.properties"
129     * file.
130     */
131    public static final String MSG_KEY_ANNOTATION_MISSING_DEPRECATED =
132            "annotation.missing.deprecated";
133
134    /**
135     * A key is pointing to the warning message text in "messages.properties"
136     * file.
137     */
138    public static final String MSG_KEY_JAVADOC_DUPLICATE_TAG =
139            "javadoc.duplicateTag";
140
141    /** {@link Deprecated Deprecated} annotation name. */
142    private static final String DEPRECATED = "Deprecated";
143
144    /** Fully-qualified {@link Deprecated Deprecated} annotation name. */
145    private static final String FQ_DEPRECATED = "java.lang." + DEPRECATED;
146
147    /** List of token types to find parent of. */
148    private static final Set<Integer> TYPES_HASH_SET = new HashSet<>(Arrays.asList(
149            TokenTypes.TYPE, TokenTypes.MODIFIERS, TokenTypes.ANNOTATION,
150            TokenTypes.ANNOTATIONS, TokenTypes.ARRAY_DECLARATOR,
151            TokenTypes.TYPE_PARAMETERS, TokenTypes.DOT));
152
153    @Override
154    public int[] getDefaultJavadocTokens() {
155        return getRequiredJavadocTokens();
156    }
157
158    @Override
159    public int[] getRequiredJavadocTokens() {
160        return new int[] {
161            JavadocTokenTypes.JAVADOC,
162        };
163    }
164
165    @Override
166    public void visitJavadocToken(DetailNode ast) {
167        final DetailAST parentAst = getParent(getBlockCommentAst());
168
169        final boolean containsAnnotation =
170            AnnotationUtil.containsAnnotation(parentAst, DEPRECATED)
171            || AnnotationUtil.containsAnnotation(parentAst, FQ_DEPRECATED);
172
173        final boolean containsJavadocTag = containsDeprecatedTag(ast);
174
175        if (containsAnnotation ^ containsJavadocTag) {
176            log(parentAst.getLineNo(), MSG_KEY_ANNOTATION_MISSING_DEPRECATED);
177        }
178    }
179
180    /**
181     * Checks to see if the javadoc contains a deprecated tag.
182     *
183     * @param javadoc the javadoc of the AST
184     * @return true if contains the tag
185     */
186    private boolean containsDeprecatedTag(DetailNode javadoc) {
187        boolean found = false;
188        for (DetailNode child : javadoc.getChildren()) {
189            if (child.getType() == JavadocTokenTypes.JAVADOC_TAG
190                    && child.getChildren()[0].getType() == JavadocTokenTypes.DEPRECATED_LITERAL) {
191                if (found) {
192                    log(child.getLineNumber(), MSG_KEY_JAVADOC_DUPLICATE_TAG,
193                            JavadocTagInfo.DEPRECATED.getText());
194                }
195                found = true;
196            }
197        }
198        return found;
199    }
200
201    /**
202     * Returns the parent node of the comment.
203     *
204     * @param commentBlock child node.
205     * @return parent node.
206     */
207    private static DetailAST getParent(DetailAST commentBlock) {
208        DetailAST result = commentBlock.getParent();
209
210        if (result == null) {
211            result = commentBlock.getNextSibling();
212        }
213
214        while (true) {
215            final int type = result.getType();
216            if (TYPES_HASH_SET.contains(type)) {
217                result = result.getParent();
218            }
219            else if (type == TokenTypes.SINGLE_LINE_COMMENT) {
220                result = result.getNextSibling();
221            }
222            else {
223                break;
224            }
225        }
226
227        return result;
228    }
229
230}