001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2019 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 java.util.Objects;
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.TokenTypes;
028
029/**
030 * <p>
031 * Check that the {@code default} is after all the {@code case}s
032 * in a {@code switch} statement.
033 * </p>
034 * <p>
035 * Rationale: Java allows {@code default} anywhere within the
036 * {@code switch} statement. But if it comes after the last
037 * {@code case} then it is more readable.
038 * </p>
039 * <p>
040 * An example of how to configure the check is:
041 * </p>
042 * <pre>
043 * &lt;module name="DefaultComesLast"/&gt;
044 * </pre>
045 */
046@StatelessCheck
047public class DefaultComesLastCheck extends AbstractCheck {
048
049    /**
050     * A key is pointing to the warning message text in "messages.properties"
051     * file.
052     */
053    public static final String MSG_KEY = "default.comes.last";
054
055    /**
056     * A key is pointing to the warning message text in "messages.properties"
057     * file.
058     */
059    public static final String MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE =
060            "default.comes.last.in.casegroup";
061
062    /** Whether to process skipIfLastAndSharedWithCaseInSwitch() invocations. */
063    private boolean skipIfLastAndSharedWithCase;
064
065    @Override
066    public int[] getAcceptableTokens() {
067        return getRequiredTokens();
068    }
069
070    @Override
071    public int[] getDefaultTokens() {
072        return getRequiredTokens();
073    }
074
075    @Override
076    public int[] getRequiredTokens() {
077        return new int[] {
078            TokenTypes.LITERAL_DEFAULT,
079        };
080    }
081
082    /**
083     * Whether to allow default keyword not in last but surrounded with case.
084     * @param newValue whether to ignore checking.
085     */
086    public void setSkipIfLastAndSharedWithCase(boolean newValue) {
087        skipIfLastAndSharedWithCase = newValue;
088    }
089
090    @Override
091    public void visitToken(DetailAST ast) {
092        final DetailAST defaultGroupAST = ast.getParent();
093        //default keywords used in annotations too - not what we're
094        //interested in
095        if (defaultGroupAST.getType() != TokenTypes.ANNOTATION_FIELD_DEF
096                && defaultGroupAST.getType() != TokenTypes.MODIFIERS) {
097            if (skipIfLastAndSharedWithCase) {
098                if (Objects.nonNull(findNextSibling(ast, TokenTypes.LITERAL_CASE))) {
099                    log(ast, MSG_KEY_SKIP_IF_LAST_AND_SHARED_WITH_CASE);
100                }
101                else if (ast.getPreviousSibling() == null
102                    && Objects.nonNull(findNextSibling(defaultGroupAST,
103                                                       TokenTypes.CASE_GROUP))) {
104                    log(ast, MSG_KEY);
105                }
106            }
107            else if (Objects.nonNull(findNextSibling(defaultGroupAST,
108                                                     TokenTypes.CASE_GROUP))) {
109                log(ast, MSG_KEY);
110            }
111        }
112    }
113
114    /**
115     * Return token type only if passed tokenType in argument is found or returns -1.
116     *
117     * @param ast root node.
118     * @param tokenType tokentype to be processed.
119     * @return token if desired token is found or else null.
120     */
121    private static DetailAST findNextSibling(DetailAST ast, int tokenType) {
122        DetailAST token = null;
123        DetailAST node = ast.getNextSibling();
124        while (node != null) {
125            if (node.getType() == tokenType) {
126                token = node;
127                break;
128            }
129            node = node.getNextSibling();
130        }
131        return token;
132    }
133
134}