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.javadoc;
021
022import java.util.regex.Pattern;
023
024import com.puppycrawl.tools.checkstyle.StatelessCheck;
025import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
026import com.puppycrawl.tools.checkstyle.api.DetailAST;
027import com.puppycrawl.tools.checkstyle.api.FileContents;
028import com.puppycrawl.tools.checkstyle.api.Scope;
029import com.puppycrawl.tools.checkstyle.api.TextBlock;
030import com.puppycrawl.tools.checkstyle.api.TokenTypes;
031import com.puppycrawl.tools.checkstyle.utils.ScopeUtil;
032
033/**
034 * <p>
035 * Checks that a variable has a Javadoc comment. Ignores {@code serialVersionUID} fields.
036 * </p>
037 * <ul>
038 * <li>
039 * Property {@code scope} - Specify the visibility scope where Javadoc comments are checked.
040 * Type is {@code com.puppycrawl.tools.checkstyle.api.Scope}.
041 * Default value is {@code private}.
042 * </li>
043 * <li>
044 * Property {@code excludeScope} - Specify the visibility scope where Javadoc
045 * comments are not checked.
046 * Type is {@code com.puppycrawl.tools.checkstyle.api.Scope}.
047 * Default value is {@code null}.
048 * </li>
049 * <li>
050 * Property {@code ignoreNamePattern} - Specify the regexp to define variable names to ignore.
051 * Type is {@code java.util.regex.Pattern}.
052 * Default value is {@code null}.
053 * </li>
054 * <li>
055 * Property {@code tokens} - tokens to check
056 * Type is {@code int[]}.
057 * Default value is:
058 * <a href="https://checkstyle.org/apidocs/com/puppycrawl/tools/checkstyle/api/TokenTypes.html#ENUM_CONSTANT_DEF">
059 * ENUM_CONSTANT_DEF</a>.
060 * </li>
061 * </ul>
062 * <p>
063 * To configure the default check:
064 * </p>
065 * <pre>
066 * &lt;module name="JavadocVariable"/&gt;
067 * </pre>
068 * <p>
069 * To configure the check for {@code public} scope:
070 * </p>
071 * <pre>
072 * &lt;module name="JavadocVariable"&gt;
073 *   &lt;property name="scope" value="public"/&gt;
074 * &lt;/module&gt;
075 * </pre>
076 * <p>
077 * To configure the check for members which are in {@code private},
078 * but not in {@code protected} scope:
079 * </p>
080 * <pre>
081 * &lt;module name="JavadocVariable"&gt;
082 *   &lt;property name="scope" value="private"/&gt;
083 *   &lt;property name="excludeScope" value="protected"/&gt;
084 * &lt;/module&gt;
085 * </pre>
086 * <p>
087 * To ignore absence of Javadoc comments for variables with names {@code log} or {@code logger}:
088 * </p>
089 * <pre>
090 * &lt;module name="JavadocVariable"&gt;
091 *   &lt;property name="ignoreNamePattern" value="log|logger"/&gt;
092 * &lt;/module&gt;
093 * </pre>
094 * <p>
095 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
096 * </p>
097 * <p>
098 * Violation Message Keys:
099 * </p>
100 * <ul>
101 * <li>
102 * {@code javadoc.missing}
103 * </li>
104 * </ul>
105 *
106 * @since 3.0
107 */
108@StatelessCheck
109public class JavadocVariableCheck
110    extends AbstractCheck {
111
112    /**
113     * A key is pointing to the warning message text in "messages.properties"
114     * file.
115     */
116    public static final String MSG_JAVADOC_MISSING = "javadoc.missing";
117
118    /** Specify the visibility scope where Javadoc comments are checked. */
119    private Scope scope = Scope.PRIVATE;
120
121    /** Specify the visibility scope where Javadoc comments are not checked. */
122    private Scope excludeScope;
123
124    /** Specify the regexp to define variable names to ignore. */
125    private Pattern ignoreNamePattern;
126
127    /**
128     * Setter to specify the visibility scope where Javadoc comments are checked.
129     *
130     * @param scope a scope.
131     */
132    public void setScope(Scope scope) {
133        this.scope = scope;
134    }
135
136    /**
137     * Setter to specify the visibility scope where Javadoc comments are not checked.
138     *
139     * @param excludeScope a scope.
140     */
141    public void setExcludeScope(Scope excludeScope) {
142        this.excludeScope = excludeScope;
143    }
144
145    /**
146     * Setter to specify the regexp to define variable names to ignore.
147     *
148     * @param pattern a pattern.
149     */
150    public void setIgnoreNamePattern(Pattern pattern) {
151        ignoreNamePattern = pattern;
152    }
153
154    @Override
155    public int[] getDefaultTokens() {
156        return getAcceptableTokens();
157    }
158
159    @Override
160    public int[] getAcceptableTokens() {
161        return new int[] {
162            TokenTypes.VARIABLE_DEF,
163            TokenTypes.ENUM_CONSTANT_DEF,
164        };
165    }
166
167    /*
168     * Skipping enum values is requested.
169     * Checkstyle's issue #1669: https://github.com/checkstyle/checkstyle/issues/1669
170     */
171    @Override
172    public int[] getRequiredTokens() {
173        return new int[] {
174            TokenTypes.VARIABLE_DEF,
175        };
176    }
177
178    @Override
179    public void visitToken(DetailAST ast) {
180        if (shouldCheck(ast)) {
181            final FileContents contents = getFileContents();
182            final TextBlock textBlock =
183                contents.getJavadocBefore(ast.getLineNo());
184
185            if (textBlock == null) {
186                log(ast, MSG_JAVADOC_MISSING);
187            }
188        }
189    }
190
191    /**
192     * Decides whether the variable name of an AST is in the ignore list.
193     *
194     * @param ast the AST to check
195     * @return true if the variable name of ast is in the ignore list.
196     */
197    private boolean isIgnored(DetailAST ast) {
198        final String name = ast.findFirstToken(TokenTypes.IDENT).getText();
199        return ignoreNamePattern != null && ignoreNamePattern.matcher(name).matches()
200            || "serialVersionUID".equals(name);
201    }
202
203    /**
204     * Whether we should check this node.
205     *
206     * @param ast a given node.
207     * @return whether we should check a given node.
208     */
209    private boolean shouldCheck(final DetailAST ast) {
210        boolean result = false;
211        if (!ScopeUtil.isInCodeBlock(ast) && !isIgnored(ast)) {
212            Scope customScope = Scope.PUBLIC;
213            if (ast.getType() != TokenTypes.ENUM_CONSTANT_DEF
214                    && !ScopeUtil.isInInterfaceOrAnnotationBlock(ast)) {
215                final DetailAST mods = ast.findFirstToken(TokenTypes.MODIFIERS);
216                customScope = ScopeUtil.getScopeFromMods(mods);
217            }
218
219            final Scope surroundingScope = ScopeUtil.getSurroundingScope(ast);
220            result = customScope.isIn(scope) && surroundingScope.isIn(scope)
221                && (excludeScope == null
222                    || !customScope.isIn(excludeScope)
223                    || !surroundingScope.isIn(excludeScope));
224        }
225        return result;
226    }
227
228}