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.coding;
021
022import com.puppycrawl.tools.checkstyle.StatelessCheck;
023import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
024import com.puppycrawl.tools.checkstyle.api.DetailAST;
025import com.puppycrawl.tools.checkstyle.api.TokenTypes;
026import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
027import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
028
029/**
030 * <p>
031 * Checks that each variable declaration is in its own statement
032 * and on its own line.
033 * </p>
034 * <p>
035 * Rationale: <a
036 * href="https://checkstyle.org/styleguides/sun-code-conventions-19990420/CodeConventions.doc5.html#a2992">
037 * the Java code conventions chapter 6.1</a> recommends that
038 * declarations should be one per line/statement.
039 * </p>
040 * <p>
041 * To configure the check:
042 * </p>
043 * <pre>
044 * &lt;module name="MultipleVariableDeclarations"/&gt;
045 * </pre>
046 * <p>
047 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
048 * </p>
049 * <p>
050 * Violation Message Keys:
051 * </p>
052 * <ul>
053 * <li>
054 * {@code multiple.variable.declarations}
055 * </li>
056 * <li>
057 * {@code multiple.variable.declarations.comma}
058 * </li>
059 * </ul>
060 *
061 * @since 3.4
062 */
063@StatelessCheck
064public class MultipleVariableDeclarationsCheck extends AbstractCheck {
065
066    /**
067     * A key is pointing to the warning message text in "messages.properties"
068     * file.
069     */
070    public static final String MSG_MULTIPLE = "multiple.variable.declarations";
071
072    /**
073     * A key is pointing to the warning message text in "messages.properties"
074     * file.
075     */
076    public static final String MSG_MULTIPLE_COMMA = "multiple.variable.declarations.comma";
077
078    @Override
079    public int[] getAcceptableTokens() {
080        return getRequiredTokens();
081    }
082
083    @Override
084    public int[] getDefaultTokens() {
085        return getRequiredTokens();
086    }
087
088    @Override
089    public int[] getRequiredTokens() {
090        return new int[] {TokenTypes.VARIABLE_DEF};
091    }
092
093    @Override
094    public void visitToken(DetailAST ast) {
095        DetailAST nextNode = ast.getNextSibling();
096
097        if (nextNode != null) {
098            final boolean isCommaSeparated = nextNode.getType() == TokenTypes.COMMA;
099
100            if (isCommaSeparated
101                || nextNode.getType() == TokenTypes.SEMI) {
102                nextNode = nextNode.getNextSibling();
103            }
104
105            if (nextNode != null
106                    && nextNode.getType() == TokenTypes.VARIABLE_DEF) {
107                final DetailAST firstNode = CheckUtil.getFirstNode(ast);
108                if (isCommaSeparated) {
109                    // Check if the multiple variable declarations are in a
110                    // for loop initializer. If they are, then no warning
111                    // should be displayed. Declaring multiple variables in
112                    // a for loop initializer is a good way to minimize
113                    // variable scope. Refer Feature Request Id - 2895985
114                    // for more details
115                    if (ast.getParent().getType() != TokenTypes.FOR_INIT) {
116                        log(firstNode, MSG_MULTIPLE_COMMA);
117                    }
118                }
119                else {
120                    final DetailAST lastNode = getLastNode(ast);
121                    final DetailAST firstNextNode = CheckUtil.getFirstNode(nextNode);
122
123                    if (TokenUtil.areOnSameLine(firstNextNode, lastNode)) {
124                        log(firstNode, MSG_MULTIPLE);
125                    }
126                }
127            }
128        }
129    }
130
131    /**
132     * Finds sub-node for given node maximum (line, column) pair.
133     *
134     * @param node the root of tree for search.
135     * @return sub-node with maximum (line, column) pair.
136     */
137    private static DetailAST getLastNode(final DetailAST node) {
138        DetailAST currentNode = node;
139        final DetailAST child = node.getLastChild();
140        if (child != null) {
141            currentNode = getLastNode(child);
142        }
143
144        return currentNode;
145    }
146
147}